Unit Test Your JavaScript Using Mocha and Chai

Unit Test Your JavaScript Using Mocha and Chai

This article was peer reviewed by Panayiotis «pvgr» Velisarakos, Mark Brown and Tom Greco. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

[…]

In this article, I’ll show you how to get started unit testing your JavaScript code. The examples and techniques shown in this article can be applied to both browser-based code and Node.js code.

[…]

The most popular practice with JavaScript code is to have a directory called test/ in your project’s root directory. Then, each test file is placed under test/someModuleTest.js. Optionally, you can also use directories inside test/, but I recommend keeping things simple — you can always change it later if necessary.

[…]

Here’s a function which adds a CSS class to an element. This should go in a new file js/className.js.

[…]

This time the test fails. You can see it in action in the following CodePen. The problem here is simple: CSS class names in elements should be separated by a space. However, our current implementation of addClass doesn’t add a space!

[…]

As you can see, testing does not have to be complicated or difficult. Just as with other aspects of writing JavaScript apps, you have some basic patterns which repeat. Once you get familiar with those, you can keep using them again and again.

[…]

If you want to continue learning this and more, I’ve created a free JavaScript unit testing quickstart series. If you found this article useful, you should definitely check it out here.

[…]