2

Using Jest and Enzyme, how can I run the code inside the setTimeout()? I also want the delay time to be considered as 0 so it won't delay my test

function being tested:

   functionToBeTested = () => {
           //more code...
            setTimeout(() => {
              console.log('not logging :/')
              return 'anything';
            }, 1000);
    }

test:

it('functionToBeTested', () => { 
    expect(functionToBeTested).toEqual('anything');
}) 
2
  • 3
    jestjs.io/docs/en/timer-mocks Jest has builtin support for this. Commented Jul 8, 2019 at 21:33
  • just mock your setTimeout function Commented Jul 8, 2019 at 21:36

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.