【问题标题】:Sinon spy callCount property returns 0 on some testsSinon spy callCount 属性在某些测试中返回 0
【发布时间】:2018-01-10 15:31:03
【问题描述】:

这是我的代码:

// SUT.spec.js
import * as myModule from './myModule';

describe('my issue', () => {
  let myFuncSpy = sinon.spy(myModule, 'myFunc');

  beforeEach(() => {
    myFuncSpy.reset();
  });

  it('my case A', () => {
    SUT.methodA();

    expect(myFuncSpy.callCount).to.equal(1);  // fails, it says it's 0
  });

  it('my case B', () => {
    SUT.methodB();

    expect(myFuncSpy.callCount).to.equal(1);  // passes

  });
});

在我的模块中,这两个方法都调用了myFunc,但是仅在methodA 上它没有被注册:

// SUT.js
import { myFunc } from './myModule';

export function methodA() {
  myFunc(....);
  console.log(myFunc.callCount); // Mocha output shows 1
};

export function methodB() {
  myFunc(....);
  console.log('method B ran');   // Mocha output shows this line
  console.log(myFunc.callCount); // Mocha output shows 1
};

基本上,间谍被调用的方式没有明显的区别。我很困惑可能是什么错误。

我在 SUT 中添加了 console.log 语句,只是为了确保正确设置了间谍(否则它不会有一个名为 callCount 的属性)。另外,如果我注释掉 .reset() 调用,日志语句会显示 undefined 而不是 1 或其他数字。

这里可能有什么问题?这当然是实际 SUT 的简化版本。但是,console.log 语句表明问题绝对不在于这些行没有被执行。

【问题讨论】:

  • 你在 methodA 中做异步操作吗?

标签: javascript unit-testing sinon


【解决方案1】:

您必须在断言之前等待您的异步方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2019-02-18
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 2017-02-04
    • 2020-11-07
    相关资源
    最近更新 更多