skip to Main Content

I am building a angular app where i want to take user JavaScript code input(ex a function), run the unit test to verify if the input code is proper and display to user if test has passed or failed. I run unit tests using angular CLI, but here i want to run tests during run time when user is using the application. It is similar to how freecodecamp runs unit tests to verify the user code input. I want to know how can i do this or is there any framework/library that supports it.

2

Answers


  1. Lets start from runnung test in browser, you can use smth like https://stackblitz.com/edit/jasmine-in-angular?file=src%2Fmain-testing.ts

    1. So you create additional entry point for running tests.
    2. Then in your main app you create textarea and allow to enter test as text.
    3. Now create iframe that points to your new entry point and send there your text, construct function and run it inside it()
    Login or Signup to reply.
  2. What you need to do in your unit tests is to actually instantiate the component and use web DOM objects and events with things like document.getElementById and such.

    Or, you can use open source libraries that make it easier. One library you might look at is testing-library/angular. While not as popular, my research concluded it’s here to stay and its probably closest to what you’re looking for.

    Personally, I prefer ng-mocks. Proper use of it runs unit tests so much faster than normal angular even though it mocks dependencies at run time because it mocks entire modules, something programmers with deadlines don’t… can’t… bother to do… but you didn’t ask about that. Specific to your question: ngNocks.click or ngMock.input make it easy. (Don’t forget to call fixture.detectChanges() to trigger component re-rendering if your test requires it.)

    The two really don’t try to compete… testing-library is focused on what you’re asking about, ng-mocks is focused on something else. However, my experience is that even though it feels like the UI helper functions in ng-mocks were thrown in as an afterthought,  they meet my needs so well that I never felt the need to look elsewhere.

    Or, if you’re looking for more than unit testing, you might want to look at web automation software like selenium for complete end-to-end testing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search