【问题标题】:Sinon spy not behaving as expected诗乃间谍行为不如预期
【发布时间】:2015-10-25 11:16:17
【问题描述】:

我在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);

【问题讨论】:

    标签: javascript unit-testing mocha.js sinon


    【解决方案1】:

    来自Sinon documentation:

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

    import 创建一个名为utilityService 的对象,它引用foobarSinon 用自己的函数替换 utilityService.bar()。但是foo 不调用utilityService.bar(),而是bar()直接。所以调用不会通过Sinon的替换函数。

    我希望它很清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 2017-04-18
      • 2015-08-29
      • 2022-07-01
      • 2023-03-29
      • 2013-11-21
      • 1970-01-01
      相关资源
      最近更新 更多