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.
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
2
Answers
Lets start from runnung test in browser, you can use smth like https://stackblitz.com/edit/jasmine-in-angular?file=src%2Fmain-testing.ts
it()
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
orngMock.input
make it easy. (Don’t forget to callfixture.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.