Skip to content

Instantly share code, notes, and snippets.

@NguyenDa18
Created July 18, 2018 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NguyenDa18/7b710d10bd9868a5eb966d6aaf71c71a to your computer and use it in GitHub Desktop.
Save NguyenDa18/7b710d10bd9868a5eb966d6aaf71c71a to your computer and use it in GitHub Desktop.
Testing Node.js with Mocha

TLDW: Testing NodeJS w/ Mocha

Fundamentals:

  • 6:00: Assertions -comparisons which throw exception upon failure
const assert = value => if (!value) throw new Error('assertion failure!')
  • 6:54: Unit Test -asserts "unit" behaves as intended, "unit" typically a function
  • 9:00: Integration Test -asserts aggregate of units or modules behave as intended (e.g. side effects done correctly, state changes etc.)

Installation Locally

  • 12:00: install as dev dependency npm i -D mocha
  • 12:22: Obligatory Test Example
module.exports = (req, res, next) => {
  req.requestTime = Date.now(); //add request timestamp to req object
  next(); //carry on
}
  • 15:13: Unit Test Example mkdir test cd test touch request-time.spec.js

Mocha Uses GLOBALS

  • 16:27: Possble reason = reduces boilerplate for tests

Create a Suite

  • 18:15: creating one
describe('requestTime middleware', function () {
  // Tests go here
});

Unit Test

  • 18:47: Mocha uses Node.js' assert module
const assert = require('assert');
const requestTime = require('../lib/request-time'); // our middleware
  • 23:54: Create a test with it(title, callback)
describe('requestTime middleware', function() {
  it('should add `requestTIme` property to req param', function() {
    // call function
    const req = {};
    requestTime(req, null, () => {});
    
    // make assertions
    assert.ok(req.requestTime > 0);
  });
});
  • 26:28: Run the test $ <app>/mocha

Integration Test

  • 32:29: Tools to use npm i -D supertest : Integration tests for express framework
const assert = require('assert');
const app = require('../app');
const request = require('supertest');

describe('GET /unix-timestamp', function() {
  it('should respond with JSON obj containing timestamp', function(done) {
    //test goes here
  });
});

"Nodeback" Style

  • 35:00: Nodeback example
  it('should respond with JSON obj containing timestamp', function(done) {
    request(app).get('/unix-timestamp')
      .expect(200).end((err, res) => {
      if (err) return done(err);
      assert.ok(res.body.timestamp < 1e10);
      done();
  });

Promise Style (Cleaner than Nodeback)

function() {
  return request(app).get('/unix-timestamp')
    .expect(200)
    .then(res => assert.ok(res.body.timestamp < 1e10));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment