Study repo for unit tests in JavaScript using the Mocha and Chai framework. I chose Mocha because it supports ESM (Jest supports only experimentally), and Chai because the tutorial I followed uses Chai for assertions.
The /examples
directory contains examples from the said tutorial (subdirectories async
and sum
), with some (mostly) minor improvements and usage comments.
The subdirectory controller
contains code from this digital ocean tutorial, which uses Sinon to easily create and assert spies, stubs and mocks.
By default (mocha test
command), Mocha runs everything in the test
directory (./test
). Personally, I prefer having my unit tests together with the files they are testing, so I name them with a .test.js
extension, and have the script
"scripts": {
"test": "mocha ./**/*.test.js"
},
in my package.json
, to just run npm test
and test all files. Note that you don't import Mocha in any code files, you just run the CLI command.
You may need to install mocha globally (npm i --global mocha
) to run the Mocha CLI
Mocha disourages using arrow functions because they bind this
to the lexical context, not the Mocha context, and Mocha likes to use this
.
c8 natively supports ESM. Install globally (npm i c8 -g
). Add to npm scripts:
"scripts": {
"test": "c8 mocha ./**/*.test.js"
},
then run npm test
to view code coverage.