我对mocha / chai / sinon很新,并且测试一般 . 我成功地测试了一个基本的快速服务器,一个返回承诺的函数,以及一个基本的续集设置来让我的鼻子湿透;但我被困在 Spy /存根/嘲笑上 .
我的拳头打嗝试图检查是否在外部模块中调用了glob:
//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 / sinon / sinon-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依赖关系以查看是否被调用?
感谢任何指针......
1 回答
你在监视glob模块本身,而不是你的
funToTest
方法中的glob调用 . 问题是glob调用是一个实现细节,实际上无法从测试中访问 . 你需要为glob回调传递一个参数,并测试它是用spy还是stub调用的 .