Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ComFreek/712a7d1488326c30f3746dd1530819e1 to your computer and use it in GitHub Desktop.
Save ComFreek/712a7d1488326c30f3746dd1530819e1 to your computer and use it in GitHub Desktop.
mocha, chai: TypeScript unit tests, synchronous & asynchronous

TypeScript unit tests

  1. npm install mocha chai ts-node typescript @types/mocha @types/chai --save-dev

  2. Edit your package.json to include:

     scripts: {
      "test": "node --harmony node_modules/mocha/bin/mocha --harmony -r ts-node/register *.spec.ts"
    }
    

    I also use --harmony since my code makes use of Symbol.asyncIterable.
    Beware that even though this builds TypeScript files your specs depend on for the first time, it does not rebuild them upon changes. My workflow is to have tsc -w running in the background and continuously run npm test.

  3. Write them, see sample.spec.ts.

Asynchronous unit tests

  1. npm install chai-as-promised @types/chai-as-promised --save-dev
  2. Write them, see sample-async.spec.ts.
import * as chai from 'chai';
import 'mocha';
import chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
const expect = chai.expect;
describe('My test suite', () => {
it('My unit test', async () => { // async keyword
const myNumber: Promise<number> = Promise.resolve(1); // Yeah, this is really TypeScript code!
// Do not forget the 'await'
await expect(myNumber).to.eventually.equal(2);
});
});
import { expect } from 'chai';
import 'mocha';
describe('My test suite', () => {
it('My unit test', () => {
const myNumber: number = 1; // Yeah, this is really TypeScript code!
expect(myNumber).to.equal(2);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment