Today I learned

Get started with Mocha testing

Testing Node.js packages is easy. Here's the condensed 1-minute guide to setting up tests on a Node.js project.

Quickstart guide

Start with a package

Make a package.json file if you don't have one yet, then install your weapons of choice.

npm init
# just keep pressing enter.
# this will create the file `package.json`
npm install --save-dev mocha chai

Write tests

Make your first test file test/my_test.js:

/* test/my_test.js */
var expect = require('chai').expect

describe('my test suite', function() {
  it('fails majestically', function() {

Update scripts

Update your package.json to use mocha.

  "scripts": {
-   "test": "echo \"Error: no test specified\" && exit 1"
+   "test": "mocha"

Run tests

Type npm test to run your tests. It should fail. Now go write tests that will pass!

  my test suite
    1) fails majestically

  0 passing (17ms)
  1 failing

  1) my test suite fails majestically:

      AssertionError: expected 3 to deeply equal 2
      + expected - actual


      test/test.js:5:18: Context.<anonymous>

Learn a bit more

Here's a quick Mocha cheatsheet. Also see

describe('test suite', function() {
  beforeEach(function() {
  afterEach(function() {

  before(function() {
  after(function() {

  it('a basic test', function() {

  it('a test with a promise', function() {
    return somePromiseObject

  it('an asynchronous test', function(next) {
    if (success) {
    } else {

  xit('use "xit" for pending tests', function() {

Expectations with Chai

Here's a quick Chai cheatsheet. See for other expect()ations.




Further reading

Use Sinon ( for mocks.

You have just read Get started with Mocha testing, written on February 13, 2015. This is Today I Learned, a collection of random tidbits I've learned through my day-to-day web development work. I'm Rico Sta. Cruz, @rstacruz on GitHub (and Twitter!).

← More articles