Front-end javascript testing with Mocha and Chai
As the interpreter becomes more and more complex, testing the program in the textarea turns into an impossible mission. To test the javascript in HTML, better to separate the javascript file from the HTML file. But the javascript file could not be tested as the Node file, you need to do a little small change to export the function you want to test.
Your javascript file:
Then you can import you function in your test class as blow:
Congratulations, you now can test your front-end javascript in your unit test case. To make it more effective I recommend Mocha and Chai as your testing framework. You can find those two framework in below website.
Both of the framework are available on npm.
Recommend adding them to package.json
file using a *
as the version tag. This will ensure that you always have the most recent version.
Tesing javascript with Mocha
All the Mocha test case file should located in the test
folder. Then we could enhance the above test case with Mocha.
Run the mocha
command in your terminal, also you can add as a test command to your package.json
file. The result will print as below:
If you want to assert an exception thrown by your function, you need to improve chai to your test cases.
Ok lets make the myFunction
throw an exception.
Then we add a test case for detect the exception:
Run again the mocha
command in your terminal, as you see, the exception has been tested.
To find more useful test function you can refer to the official document of Mocha and Chai, this should helpful to test your frond-end javascript:)