[英]How to get inside a setTimeout function using jest
使用 Jest 和 Enzyme,如何在 setTimeout() 中运行代码? 我还希望将延迟时间视为 0,因此它不会延迟我的测试
正在测试的功能:
functionToBeTested = () => {
//more code...
setTimeout(() => {
console.log('not logging :/')
return 'anything';
}, 1000);
}
测试:
it('functionToBeTested', () => {
expect(functionToBeTested).toEqual('anything');
})
这是单元测试解决方案:
index.ts
:
export const functionToBeTested = () => {
return new Promise(resolve => {
setTimeout(() => {
console.log('not logging :/');
resolve('anything');
}, 1000);
});
};
index.spec.ts
:
import { functionToBeTested } from './';
jest.useFakeTimers();
test('should return correctly', async () => {
const logSpy = jest.spyOn(console, 'log');
const promise = functionToBeTested();
jest.runAllTimers();
await expect(promise).resolves.toBe('anything');
expect(logSpy).toBeCalledWith('not logging :/');
});
100% 覆盖率的单元测试结果:
PASS src/stackoverflow/56942805/index.spec.ts (8.036s)
✓ should return correctly (10ms)
console.log node_modules/jest-mock/build/index.js:860
not logging :/
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.608s
源代码: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56942805
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.