Sinon spy callCount属性在某些测试中返回0

问题描述 投票:2回答:1

这是我的代码:

// 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语句表明问题绝对不是线路没有被执行。

javascript unit-testing sinon
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.