Mocha and Istanbul in 5 minutes
Who is this for?
This post is for you if:
- you want to get started with tests and test coverage but
feel overwhelmed by the details
or
- you already know all this… but will appreciate a “checklist”
next time you need to do it all again
I was in the second situation recently and decided to write everything down while it’s still fresh.
Context
You have a Node.js project, but no tests (yet), and you need just enough to get started.
- Mocha is test framework.
- Istanbul is a test coverage tool.
nyc
is the command-line client for Istanbul.
I put all the files you’ll need on github.
This is not a tutorial on how to write tests or how to use Mocha/Istanbul … but there are some pointers at the end of the post.
Step by step
1. Install your dependencies
2. Create the test directory
3. Create a file to test
4. Edit scripts in package.json
Open your package.json
and make sure the scripts
section looks like:
5. Run your tests
6. Run your test coverage
Overtime
We have tests, we can run them, and we have test coverage: done!
Comments:
Test coverage is poor, on purpose; to show you how useful Istanbul can be:
In this case, you would need more tests:
What’s describe
and it
? Refer to the excellent mocha documentation.
Mocha, by default, runs tests from test/*.js
, that’s why we didn’t need to specify test files or directories.
I kept things simple and used Node.js’s assert library.
When things get complicated, you’ll probably need sinon. Here’s a good tutorial.