gpt4 book ai didi

javascript - sinon 监听回调

转载 作者:行者123 更新时间:2023-12-02 21:52:12 24 4
gpt4 key购买 nike

我觉得我大致了解 sinon 的工作原理,但在监视传递给我正在测试的导入函数的回调时遇到了一些麻烦。这是一个例子:

import sinon from 'sinon'

const callbackCaller = (cb: (msg:string) => void, msg: string) => {
cb(`CallbackCaller called with ${cb}, ${msg}`)
}

describe('This seems wrong', () => {
it('should pass but doesn\'t', () => {
const callback = (msg: string) => {
console.log(`Callback called with ${msg}`)
}

const callbackSpy = sinon.spy(callback)

callbackCaller(callback, 'tarfu')
sinon.assert.called(callbackSpy)
})
})

运行时,此测试按预期打印,但断言失败:

$ yarn test:failure

yarn run v1.21.1
$ jest src/test.test.ts
FAIL src/test.test.ts
This seems wrong
✕ should pass but doesn't (8ms)

● This seems wrong › should pass but doesn't

AssertError: expected callback to have been called at least once but was never called

14 |
15 | callbackCaller(callback, 'tarfu')
> 16 | sinon.assert.called(callbackSpy)
| ^
17 | })
18 | })
19 |

at Object.fail (../../../node_modules/sinon/lib/sinon/assert.js:107:21)
at failAssertion (../../../node_modules/sinon/lib/sinon/assert.js:66:16)
at Object.assert.(anonymous function) [as called] (../../../node_modules/sinon/lib/sinon/assert.js:92:13)
at Object.it (test.test.ts:16:22)

console.log src/test.test.ts:10
Callback called with CallbackCaller called with (msg) => {
console.log(`Callback called with ${msg}`);
}, tarfu

Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.815s, estimated 1s
Ran all test suites matching /src\/test.test.ts/i.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

请注意,回调确实正在被调用,正如它在堆栈跟踪下方打印所证明的那样。我使用的是节点版本 10.16 和 jest 25.1.0。由于回调是在失败后记录的,所以看起来有点像 Jest 在 callbackCaller 调用 cb 之前检查 spy ,但没有异步的东西,所以我有点在损失。希望解决方案不是“sinon 不使用其他工具来执行此操作”:)

最佳答案

您应该将 callbackSpy 传递给 callbackCaller 函数,而不是原始的 callback。因为sinon用spy(callbacksSpy)包装了callback,这样你就可以使用sinon.assert.called来断言它。

index.test.ts:

import sinon from 'sinon';

const callbackCaller = (cb: (msg: string) => void, msg: string) => {
cb(`CallbackCaller called with ${cb}, ${msg}`);
};

describe('This seems wrong', () => {
it("should pass but doesn't", () => {
const callback = (msg: string) => {
console.log(`Callback called with ${msg}`);
};

const callbackSpy = sinon.spy(callback);

callbackCaller(callbackSpy, 'tarfu');
sinon.assert.called(callbackSpy);
});
});

单元测试结果:

This seems wrong
Callback called with CallbackCaller called with callback, tarfu
✓ should pass but doesn't


1 passing (6ms)

关于javascript - sinon 监听回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60105325/

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