使用Jest和Enzyme,如何在setTimeout()中运行代码?我也希望将延迟时间视为0,这样才不会延迟测试
正在测试的功能:
functionToBeTested = () => {
//more code...
setTimeout(() => {
console.log('not logging :/')
return 'anything';
}, 1000);
}
测试:
it('functionToBeTested', () => {
expect(functionToBeTested).toEqual('anything');
})
答案 0 :(得分:0)
这是单元测试解决方案:
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