gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:28:28 26 4
gpt4 key购买 nike

这是我的代码:

// 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
};

spy 的调用方式基本上没有明显区别。我很困惑,因为可能有什么问题。

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

这里有什么问题?这当然是实际 SUT 的简化版本。但是,console.log 语句显示问题绝对不是行没有被执行。

最佳答案

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

关于javascript - Sinon spy callCount 属性在某些测试中返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48190848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com