準備
必要なnpmは以下
- mocha
- chai
- sinon (※ sinon-chai入れてもsinonは別に必要?)
- sinon-chai
var chai = require('chai'),
should = chai.should(),
sinon = require('sinon'),
sinonChai = require('sinon-chai');
chai.use(sinonChai);
非同期テスト
beforeやitの引数のfunctionはdoneが引数としてとれるので、テストを次に進めていいタイミングで呼び出す。doneを引数としてとらなければ、そのまま進む。
asyncronize.js
it("should not raise an error", function(done) {
fs.readFile("/path/to/text.text", function(err, data) {
should.not.exist(err);
done();
});
})
hooks
before
テスト実行前に'一度だけ'走る
describe('test', function() {
before(function(done) {
console.log('before');
done();
});
it('should be done successfull', function() {
console.log('it1');
});
it('should be done successfull', function() {
console.log('it2');
});
});
before
it1
it2
beforeEach
テスト実行前に'毎it'走る
describe('test', function() {
beforeEach(function(done) {
console.log('before');
done();
});
it('should be done successfull', function() {
console.log('it1');
});
it('should be done successfull', function() {
console.log('it2');
});
});
before
it1
before
it2
after
テスト実行後に'一度だけ'はしる
before の対応
afterEahc
テスト実行後に'毎it'はしる
beforeEach の対応
アサーション(chai)
should使う場合のアサーション一覧
http://chaijs.com/api/bdd/
少しだけピックアップ
deep
Object同士を比べる場合はequalでは無くこちらを使う
var obj = {a: "b"};
obj.should.deep.equal({a: "b"});
stub, mock
sinonを使ってstub(mock)する。
describe('Send data', function() {
var spy, target;
before(function() {
spy = sinon.spy();
target = new TestTargetModule();
target._sendData = spy;
});
it("should sends data over private _sendData method", function() {
target.send('data');
spy.should.have.been.calledWith('data');
});
it("should not sends data over private _sendData method", function() {
target.send('data', {direct: true});
spy.should.not.have.been.calledWith('data');
});
});