Portable Javascript Unit Testing with Mocha and Chai

Portable Javascript Unit Testing with Mocha and Chai

If you came here to see the words npm install, webpack, etc then this is the wrong post. I’m not a big fan of build tools or installing things I don’t need to. I’m partial to minimalistic development environments. They keep you focused on what matters – the actual development and programming.

Unit testing can be a huge time saver by combating code complexity in projects. I like to think of them as “notes” to my actual code. They describe what a function should and should not be doing. As a result, you are building reusable, reliable code snippets for other projects.

If you want a lightweight Javascript test environment, use the following

It requires one useful Atom plugin and some boiler code. No nodeJS needed. Only Javascript files hosted by Cloudflare’s CDN. As a project gets more complex, you can add build tools but keep the testing syntax the same.

The boilerplate codepen for unit testing is below

See the Pen Unit Testing JS with Mocha by Vincent Tang (@Kagerjay) on CodePen.32127

Below is a javascript calculator I wrote using it. It was originally written via Atom.

See the Pen Javascript Calculator Pt1 with Unit Tests by Vincent Tang (@Kagerjay) on CodePen.32127

There’s many ways to unit tests. But I prefer this one. Its simple and it works. Some suggestions when working with chai/mocha / unit-testing in general.

  • Use a separate file for unit tests – I use a script.test.js to test script.js . It is intuitive. This makes for cleaner commits. You can find how I organized it on  my github
  • Display the unit tests in the browser – You can have your unit tests displayed in the chrome console. Or locally, at the command prompt. I prefer to put in the browser since I only need to look at 2 things during development – my IDE and browser.
  • Put the unit tests at the bottom of file – Unit tests are sometimes longer than the source code itself.
  • Use chai’s assertion library – method calls found on chaijs.com. Use assert over  should and expect since it follows lambda calculus principles.
  • Write in a functional programming style – its easier to test functions when it has a clear input and output. Iterative programming is hard to unit-test.


Leave a Reply

Your email address will not be published. Required fields are marked *