rogerxu / rogerxu.github.io

Roger Xu's Blog
2 stars 2 forks source link

Mocha #120

Open rogerxu opened 7 years ago

rogerxu commented 7 years ago

Mocha - the fun, simple, flexible JavaScript test framework

rogerxu commented 7 years ago

Usage

https://mochajs.org/#usage

Run tests in directory test for *.js files.

mocha

Run tests in another directory

mocha --recursive "test/unit"

Run tests for ES6 modules with extension .js

mocha --compilers js:babel-register

Require ES6 polyfills

mocha --require babel-polyfill

You can put command options in test/mocha.opts

--compilers js:babel-register
--require babel-polyfill
--recursive
test/unit

Debug

$ mocha --inspect --debug-brk

devtool

# run a mocha test
$ devtool node_modules/mocha/bin/_mocha -qc -- ./tests/my-spec.js
rogerxu commented 7 years ago

Test

Synchronous Code

describe('Array', function () {
  describe('#indexOf()', function () {
    it('should return -1 when the value is not present', function () {
      expect([1, 2, 3].indexOf(4)).to.equal(-1);
    });
  });
});

Asynchronous Code

describe('#find()', function () {
  it('respond with matching records', function (done) {
    return db.find({ type: 'User' }).then(done);
  });
});

Promise

Chai Assertions for Promises - Chai

Promises in JavaScript Unit Tests: the Definitive Guide

describe('#find()', function () {
  it('respond with matching records', function (done) {
    return db.find({ type: 'User' }).should.eventually.have.length(3);
  });
});