mocha 和 co-mocha

mocha 是一个流行的 Node.js 测试框架,它同时支持 TDD、BDD 和 exports 风格的测试,并且支持许多优秀的断言库,支持异步和同步的测试,支持多种方式导出结果,同时也支持浏览器端的测试。

mocha 的 BDD 支持 describe()context()it()before()after()beforeEach()afterEach();TDD 支持 suite()test()suiteSetup()suiteTeardown()setup()teardown(),具体使用见 mocha 官方网站

我们常用的有 describe()it()

  • describe: 用来描述一组测试的目的或功能,可以嵌套。
  • it: 用来描述测试的期望值,一个 describe 可以有多个 it,一个 it 至少有一个断言。

mocha 的官方 BDD 示例:

$ npm install -g mocha
$ mkdir test
$ vim test/test.js

var assert = require("assert")
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    })
  })
})

$ mocha

Array
  #indexOf()
    ✓ should return -1 when the value is not present

1 passing (12ms)

这里使用了 Node.js 自带的断言库 Assert,npm 上还有些流行的断言库如 should.js, chai 和 expect.js,我们使用 should.js 改写如下:

var should = require("should")
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      [1,2,3].should.not.containDeep(5);
      [1,2,3].should.not.containDeep(0);
    })
  })
})

$ mocha

Array
  #indexOf()
    ✓ should return -1 when the value is not present

1 passing (12ms)

可以看出,使用 should.js 可以写出十分语意化的测试代码。

co-mocha 是一个 mocha 经过 co 库包装后以支持生成器函数的库。使用方式跟 mocha 类似:

var should = require("should")
describe('User', function(){
  describe('.addUser', function(){
    it('should return user object contains `name`', function* (){
      var user = yield User.addUser({name: 'nswbmw'});
      should(user).have.property('name', 'nswbmw');
    })
  })
})

supertest 和 co-supertest

supertest 是一个 HTTP 断言库,使用它可以测试 HTTP 服务,如使用 express、koa 搭建的服务等。结合 express 使用如下:

var request = require('supertest')
  , express = require('express');

var app = express();

app.get('/user', function(req, res){
  res.status(200).send({ name: 'tobi' });
});

describe('express', function () {
  it('GET /user', function (done) {
    request(app)
      .get('/user')
      .expect('Content-Type', /json/)
      .expect('Content-Length', '15')
      .expect(200, done);
  });
});

$ mocha test.js

express
  ✓ GET /user (50ms)

1 passing (60ms)

co-supertest 是一个 supertest 经过 co 库包装后以支持生成器函数的库。使用方法也跟 supertest 类似,结合 co-mocha 使用如下:

var request = require('co-supertest')
  , koa = require('koa');

var app = koa();

app.use(function* () {
  this.body = { name: 'tobi' };
});

describe('koa', function () {
  it('GET /user', function* () {
    yield request(app.callback())
      .get('/user')
      .expect('Content-Type', /json/)
      .expect('Content-Length', '15')
      .expect(200)
      .end();
  });
});

$ mocha --require co-mocha test.js

koa
  ✓ GET /user (46ms)

1 passing (58ms)