我对mocha / chai / sinon很新,并且测试一般。我成功地测试了一个基本的快速服务器,一个返回承诺的函数,以及一个基本的续集设置来让我的鼻子湿透;但我被困在间谍/存根/嘲笑上。
我的第一个打嗝是试图检查外部模块中是否已调用blob:
//in utils.js
var glob = require('glob');
module.exports = {
funToTest: function (msg, callback) {
console.log(msg);
glob('*md', {
cwd: 'files/'
}, function (err, files) {
console.log(files);
});
callback();
callback();
}
};
使用mocha / chai / otherwise / if-chai组合:
// in utils-test.js
var utils = require('utils.js');
var glob = require('glob');
describe('Utils', function () {
describe('funToTest method', function () {
const callback = sinon.spy();
const globSpy = sinon.spy(glob);
before(function (done) {
utils.funToTest('Files:', callback);
done();
});
// This PASSES fine
it ('should call our callback twice', function () {
expect(callback).to.have.been.calledTwice;
});
// This NOT SO MUCH
it('should call glob once', function () {
expect(globSpy).to.have.been.calledOnce;
});
)};
)};
以上失败并出现断言错误:
AssertionError: expected glob to have been called exactly once, but it was called 0 times
那么我如何监视utils.funToTest中的glob依赖关系以查看是否被调用?
感谢任何指针......
你在监视glob模块本身,而不是你的funToTest
方法中的glob调用。问题是glob调用是一个实现细节,实际上无法从测试中访问。你需要为glob回调传递一个参数并测试它是用spy还是stub调用的。
//in utils.js
var glob = require('glob');
module.exports = {
funToTest: function (msg, globCb, callback) {
glob('*md', {
cwd: 'files/'
}, globCb);
callback();
callback();
}
};
// in utils-test.js
var utils = require('utils.js');
var glob = require('glob');
describe('Utils', function () {
describe('funToTest method', function () {
const callback = sinon.spy();
const globCb = sinon.spy();
const err = {err: 'Error'};
const files = ['file1', 'file2'];
before(function (done) {
utils.funToTest('Files:', globCb, callback);
done();
});
// Should still pass
it ('should call our callback twice', function () {
expect(callback).to.have.been.calledTwice;
});
// Passes with correct args
it('should call glob once', function () {
expect(globCb).to.have.been.calledOnce;
// inspect the arg values with .calledWithArgs
expect(globCb.calledWithArgs(err, files)).to.be.true;
// inspect the arg values with .getCall(index) (actually grabs the call args on the first call to globSpy)
expect(globCb.getCall(0).args[0]).to.equal(err);
expect(globCb.getCall(0).args[1]).to.equal(files);
});
)};
)};