Here is the unit test solution:
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 :/');
});
Unit test result with 100% coverage:
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
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56942805