Skip to content

Testing the use of Promises with setTimeout in useEffect hook #241

Closed
@erikshestopal

Description

@erikshestopal

Hey there! I'm having an issue testing a custom hook that uses an async function in the useEffect hook. If I try to await a promise inside of the run function, my test times out if I use waitForNextUpdate. What am I doing wrong and how can I fix this behavior?

import { renderHook, act } from '@testing-library/react-hooks';
import { useState, useEffect, useContext } from 'react';

// using fake timers 
jest.useFakeTimers();

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const run = async () => {
      // await Promise.resolve(); // If I remove this line, test passes.

      setTimeout(() => {
        setCount(count => count + 1);
      }, 5000);
    };

    run();
  }, []);

  return { count };
}

test('it should work', async () => {
  const { result, waitForNextUpdate } = renderHook(() => Counter());

 act(() => {
    jest.runAllTimers();
  });

// await waitForNextUpdate(); this line triggers the Jest 5000ms timeout error. 

  expect(result.current.count).toEqual(1);
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingrequest for commentDiscussion about changes to the library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions