我尝试使用mocha,chai和sinon测试是否在某些条件下调用特定方法。这是代码:
function foo(in, opt) {
if(opt) { bar(); }
else { foobar(); }
}
function bar() {...}
function foobar() {...}
module.exports = {
foo: foo,
bar: bar,
foobar:foobar
};
以下是我的测试文件中的代码:
var x = require('./foo'),
sinon = require('sinon'),
chai = require('chai'),
expect = chai.expect,
should = chai.should(),
assert = require('assert');
describe('test 1', function () {
it('should call bar', function () {
var spy = sinon. spy(x.bar);
x.foo('bla', true);
spy.called.should.be.true;
});
});
当我对间谍做一个console.log时,它表示即使你通过手动登录条形码我也无法调用它,我能够看到它被调用。关于我可能做错什么或怎么做的任何建议?
由于
答案 0 :(得分:7)
您已创建了spy
,但测试代码并未使用它。用您的间谍替换原来的x.bar
(不要忘记清理!)
describe('test 1', function () {
before(() => {
let spy = sinon.spy(x.bar);
x.originalBar = x.bar; // save the original so that we can restore it later.
x.bar = spy; // this is where the magic happens!
});
it('should call bar', function () {
x.foo('bla', true);
x.bar.called.should.be.true; // x.bar is the spy!
});
after(() => {
x.bar = x.originalBar; // clean up!
});
});