【发布时间】:2020-05-23 02:39:25
【问题描述】:
我觉得我大致了解 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。由于回调是在失败后记录的,所以看起来开玩笑是在 callbackCaller 调用 cb 之前检查间谍,但没有异步的东西,所以我有点不知所措。希望解决方案不是“sinon 不使用其他工具”:)
【问题讨论】:
标签: javascript typescript unit-testing jestjs sinon