All notes
Mochajs

Intro

References

Mocha, Chai, Sinon

docs.cypress.io.

Mocha’s bdd syntax, which fits perfectly with both integration and unit testing. It provides us a framework to structure our tests.

Chai gives us the ability to easily write assertions.
BDD (expect/should) and TDD (assert).

Sinon provides ability to stub and spy methods.

Simple examples



var assert = require('assert'); // Use Node.js’ built-in assert module.
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal([1,2,3].indexOf(4), -1);
    });
  });
});

// Back in the terminal:
// ./node_modules/mocha/bin/mocha

Test asynchronous codes



describe('User', function() {
  describe('#save()', function() {
    it('should save without error', function(done) {
      var user = new User('Luna');
      user.save(function(err) {
        if (err) done(err);
        else done();
      });
    });
  });
});

// To make things even easier, the done() callback accepts an error, so we may use this directly:
describe('User', function() {
  describe('#save()', function() {
    it('should save without error', function(done) {
      var user = new User('Luna');
      user.save(done);
    });
  });
});

Exclusive tests, it.only



// Executing only a particular suite:
describe('Array', function() {
  describe.only('#indexOf()', function() {
    // ...
  });
});

// Executing an individual test case:
describe('Array', function() {
  describe('#indexOf()', function() {
    it.only('should return -1 unless present', function() {
      // this test will be run
    });

    it('should return the index when present', function() {
      // this test will not be run
    });
  });
});

Inclusive tests, it.skip



it.skip('should return -1 unless present', function() {
  // this test will not be run
});