诗乃间谍行为不如预期

时间:2015-10-25 11:16:17

标签: javascript unit-testing mocha sinon

我在utilityService.js中有两个函数foo和bar

export function foo() {
    return bar();
}

export function bar() {
    return 1;
}

在我的测试文件中,我导入了utilityService.js并监视了bar函数。 我希望spy的callCount为1,因为foo被调用但它是0.请建议我是否遗漏了任何东西。

import * as utilityService from '../services/utility-service';

let callSpy = sinon.spy(utilityService, 'bar');
expect(utilityService.foo()).to.equal(1);
expect(callSpy.callCount).to.equal(1);

1 个答案:

答案 0 :(得分:1)

来自Sinon documentation:

  

sinon.spy(object," method")为object.method创建一个间谍,并用spy替换原始方法。

import创建一个名为utilityService的对象,该对象引用foobarSinon用自己的函数替换utilityService.bar()。但是foo并未调用utilityService.bar(),而bar() 直接调用。因此,通话不会通过Sinon替换的功能。

我希望它清楚。