在module.exports方法中使用sinontesting方法调用

我试图testing一下,如果使用摩卡,柴和颂,给定了某些特定的条件。 这里是代码:

function foo(in, opt) { if(opt) { bar(); } else { foobar(); } } function bar() {...} function foobar() {...} module.exports = { foo: foo, bar: bar, foobar:foobar }; 

这是我的testing文件中的代码:

 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它说,即使你用手动日志logging方法,我也能看到它被调用。 有什么我可能会做错的build议或如何去做呢?

谢谢

您创build了一个spy ,但testing代码不使用它。 用你的间谍replace原来的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! }); });