Skip to content

waitFor doesn't work if jest fake timers are used #631

Open

Description

@DennisSkoko
  • react-hooks-testing-library version: 7.0.0
  • react version: 17.0.2
  • react-dom version: 17.0.2
  • node version: 14.16.0
  • npm version: 7.10.0

Problem

When using waitFor when Jest has been configured to use fake timers then the waitFor will not work and only "polls" once. After that the test just hangs until Jest comes in and fails the test with that the test exceeds the timeout time. Below is some code that showcases the problem.

import { renderHook } from '@testing-library/react-hooks'

it('does not work', async () => {
  jest.useFakeTimers()

  const { waitFor } = renderHook(() => {})

  await waitFor(() => {
    console.log('poll') // Is printed just once
    expect(false).toBe(true)
  }, { timeout: 25, interval: 10 })

  // Fails with Exceeded timeout of 5000 ms for a test.
})

Basically the waitFor from @testing-library/react-hooks is using the faked setTimeout or setInterval which prevents it from working correctly.

There is a workaround (see suggested solution) but I recommend providing a nice error message when waitFor is used together with faked timers or maybe change the implemenation so it will work with fake timers.

Suggested solution

I found this issue and it seems that person has already been fixed in @testing-library/dom. From my perspective I can suggest maybe reuse that function instead of implementing it yourselves but I don't really know the internal structure / code.

But after finding that issue and realizing that is has been fixed there, then I use the following code as a workaround which works fine.

import { waitFor } from '@testing-library/react'

it('works', async () => {
  jest.useFakeTimers()

  await waitFor(() => {
    console.log('poll') // Is printed twice
    expect(false).toBe(true)
  }, { timeout: 25, interval: 10 })

  // Fails with false is not equal to true
})

A more real world scenario

If curios on the actual problem I'm facing is to test the following hook:

function useSomething({ onSuccess }) {
  const poll = useCallback(async () => {
    const result = await fetch(/* ... */)
    if (result.ok) onSuccess()
  }, [onSuccess])

  useEffect(() => {
    const id = setInterval(() => { poll() }, 2000)
    return () => clearInterval(id)
  }, [poll])
}

What I want to do is test that it invokes the onSuccess function on a successfull poll.

it('invokes the `onSuccess` on successfull poll', async () => {
  const onSuccess = jest.fn()
  jest.useFakeTimers()

  const { waitFor } = renderHook(() => useSomething({ onSuccess }))

  jest.runOnlyPendingTimers()
  await waitFor(() => expect(onSuccess).toHaveBeenCalled())
})

Activity

  1. added
    bug
    on May 27, 2021
  2. mpeyper commented on May 28, 2021

    @mpeyper
    Member

    When I was reading this I was thinking the only way I could think of solving it would be to query jest about the timers, so it's interesting that that's effectively how they solved it in dom-testing-library.

    Unfortunately we can use the same function as we do not depend on it, or the DOM in general, which their solution uses. That said, the way we waitFor is similar so we can likely take some clues from them.

    If anyone is interested in working on the fix for this, I'm more than happy the help you out.

  3. chris110408 commented on Jun 8, 2021

    @chris110408
    Contributor

    @mpeyper
    I would like to contribute, I think the outline for this solution will be a similar solution used by dom-testing-library

    1. We detect if we're in an environment that's faking out timers.
      for this step, I have a question, should we use their helper or we need helps by ourselves for the jestFakeTimersAreEnabled function and the setImmediateFn
      function jestFakeTimersAreEnabled() {
        return hasJestTimers()
            ? usedFakeTimers
            :false
      }
    
    
     function hasJestTimers() {
        return (
            typeof jest !== 'undefined' &&
            jest !== null &&
            typeof jest.useRealTimers === 'function'
        )
      }
    
      const usedFakeTimers = Object.entries(timerAPI).some(
          ([name, func]) => func !== globalObj[name],
      )
    
    const globalObj = typeof window === 'undefined' ? global : window
    
    
    let   setImmediateFn = globalObj.setImmediate || setImmediatePolyfill,
    
    function setImmediatePolyfill(fn) {
      return globalObj.setTimeout(fn, 0)
    }
    1. Revise wait function
     const wait = async (callback: () => boolean | void, { interval, timeout }: WaitOptions) => {
        ....
       const waitForFakeTimer=async (interval)=>{
          let finished = false
          while (!finished) {
            if (!jestFakeTimersAreEnabled()) {
               throw new Error(
                  `Changed from using fake timers to real timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to real timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`,
              )
            }
            jest.advanceTimersByTime(interval)
            await new Promise(r => setImmediate(r))
          }
        }
      ....
        if (!checkResult()) {
         
       ....
          await act(() => Promise.race([waitForResult(), timeoutPromise(),usingJestFakeTimers && waitForFakeTimer(interval)].filter(Boolean)))
          } else {
            await act(() => Promise.race([waitForResult(),usingJestFakeTimers && waitForFakeTimer(interval)].filter(Boolean)))
          }
    
    }
  4. mpeyper commented on Jun 9, 2021

    @mpeyper
    Member

    Sorry for the delay in responding @chris110408. Any contributions towards this are very welcome.

    I think taking a similar approach to dom-testing-library is a good idea and I proposed solution seems fine to me (assuming it works).

    My only other thought is the inclusion of timeoutPromise() or not in the race feels like it could be achievable with the .filter(Boolean) as well, but I'll hold judgement on the readability until the PR 😉.

  5. chris110408 commented on Jun 9, 2021

    @chris110408
    Contributor

    Thanks @mpeyper I will work on the PR

  6. chris110408 commented on Jun 15, 2021

    @chris110408
    Contributor

    I have been trying to find the fix for a typescript error.
    image
    I am not sure how to fix it yet. and I am not able to use // @ts-ignore to quickly fix it.
    I guess I also should not use // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error 😄
    @mpeyper I need some help for this problem

  7. mpeyper commented on Jun 15, 2021

    @mpeyper
    Member

    Give this a shot:

      Object.entries(timerAPI).some(
        ([name, func]) =>  func !== globalObj[name as keyof typeof timerAPI]
      )

    Object.entries returns [string, T][] so you need to destructure the tuple (the ([name, func]) => ... change) and the first index of the tuple is annoyingly a string instead the the keys of the object (there are reasons for this though, so it needs to be cast in order to use it as an index of globalObj.

    Hope this helps.

  8. chris110408 commented on Jun 15, 2021

    @chris110408
    Contributor

    Give this a shot:

      Object.entries(timerAPI).some(
        ([name, func]) =>  func !== globalObj[name as keyof typeof timerAPI]
      )

    Object.entries returns [string, T][] so you need to destructure the tuple (the ([name, func]) => ... change) and the first index of the tuple is annoyingly a string instead the the keys of the object (there are reasons for this though, so it needs to be cast in order to use it as an index of globalObj.

    Hope this helps.

    It works
    Thanks a lot for the explanation

  9. chris110408 commented on Jun 18, 2021

    @chris110408
    Contributor

    @mpeyper
    I has been working on this issue recently,
    I changed the fackerTimer detection code to this

    const usedFakeTimers = ()=>!!(global.setTimeout.mock||global.setTimeout.clock)

    However, I have a hard time to understand the issue,

    import { renderHook } from '@testing-library/react-hooks'
    
    it('does not work', async () => {
      jest.useFakeTimers()
    
      const { waitFor } = renderHook(() => {})
    
      await waitFor(() => {
        console.log('poll') // Is printed just once
        expect(false).toBe(true)
      }, { timeout: 25, interval: 10 })
    
      // Fails with Exceeded timeout of 5000 ms for a test.
    })

    this test will never pass no matter we use useFakeTimers or not.

    and I change the test code to

    it('useFakeTimers test', async () => {
            jest.useFakeTimers()
            const { waitFor } = renderHook(() =>{})
    
            let actual = 0
            const expected = 1
    
            setTimeout(() => {
                    actual = expected
            }, 200)
    // show Fails with Exceeded timeout of 5000 ms for a test. if we do not use  jest.advanceTimersByTime(200)
            jest.advanceTimersByTime(200)
            let complete = false
            await waitFor(() => {
                    expect(actual).toBe(expected)
                    complete = true
            },{ interval: 50 })
            expect(complete).toBe(true)
    })

    our test library does not have any problem running it.

    Could you please help me confirm what is our problem here?

    Should I just add this unit test to prove waitFor works when using jest.useFakeTimers() ?

  10. mpeyper commented on Jun 18, 2021

    @mpeyper
    Member

    To be honest, I don't use fake timers when I write tests, so I'm also unsure of what the desired outcome is.

    I think the difference you have here is advanceTimersByTime is going to advance the internal timers as well, even as new timers are created for the different intervals, but runOnlyPendingTimers will only advance existing timers and the new ones never advance.

    @DennisSkoko is there more info you can provide to help @chris110408 out?

  11. chris110408 commented on Jun 18, 2021

    @chris110408
    Contributor

    To be honest, I don't use fake timers when I write tests, so I'm also unsure of what the desired outcome is.

    I think the difference you have here is advanceTimersByTime is going to advance the internal timers as well, even as new timers are created for the different intervals, but runOnlyPendingTimers will only advance existing timers and the new ones never advance.

    @DennisSkoko is there more info you can provide to help @chris110408 out?

    @DennisSkoko @mpeyper

    I add another test that uses the runOnlyPendingTimers and useFakeTimer and both test successfully pass

  12. mpeyper commented on Jun 18, 2021

    @mpeyper
    Member

    Now I'm even more confused about what the actual issue is here. There must be a reason dom-testing-library has such an implementation?

    Do they want it to work automagically without explicitly advancing the timers? (Some of the samples provided imply this)

  13. chris110408 commented on Jun 21, 2021

    @chris110408
    Contributor

    Now I'm even more confused about what the actual issue is here. There must be a reason dom-testing-library has such an implementation?

    Do they want it to work automagically without explicitly advancing the timers? (Some of the samples provided imply this)

    I am also confused about the actual issue. Yes, the dom-testing-library solution is useFakeTimer and without explicitly advancing the timers? in the test. However, I think it is comment practice to use advanceTimersByTime when use useFakeTimeber in the test. (I have not to use useFakeTimer before. my assumption was made by reading the Jest document the timer mock is used for setting up a testing environment not depend on real-time to elapse and jest mock timer functions that allow you to control the passage of time ) and I am not sure why they make it work automagically without explicitly advancing the timers? Please let me know if you want me to make the wait for function of react-hooks-testing-library works in that way.

  14. DennisSkoko commented on Jun 21, 2021

    @DennisSkoko
    Author

    Hi @chris110408 @mpeyper, sorry for the late response.

    From my point of view, what is happening is that the implementation of waitFor is using the setTimeout/setInterval which are mocked when useFakeTimers is used, resulting in the polling logic for waitFor will just hang.

    and I change the test code to

    it('useFakeTimers test', async () => {
            jest.useFakeTimers()
            const { waitFor } = renderHook(() =>{})
    
            let actual = 0
            const expected = 1
    
            setTimeout(() => {
                    actual = expected
            }, 200)
    // show Fails with Exceeded timeout of 5000 ms for a test. if we do not use  jest.advanceTimersByTime(200)
            jest.advanceTimersByTime(200)
            let complete = false
            await waitFor(() => {
                    expect(actual).toBe(expected)
                    complete = true
            },{ interval: 50 })
            expect(complete).toBe(true)
    })

    our test library does not have any problem running it.

    I think the reason this works fine is that the waitFor will never fail in this case. You are advancing time before invoking the waitFor which will result in the initial poll being successful. Here is hopefully a better example that showcases the problem:

    it('asd', async () => {
      jest.useFakeTimers()
    
      const fn = jest.fn().mockReturnValueOnce(false).mockReturnValueOnce(true)
    
      const { waitFor } = renderHook(() => {})
    
      await waitFor(() => {
        expect(fn()).toBe(true)
      })
    })

    Here we can see that test cases fails with a Jest timeout. Reason being that waitFor does an initial poll that checks in the function does not throw, but in this case it will since false does not equal true. As soon as the initial poll from waitFor fails, then waitFor will use setTimeout/setInterval to poll. Now our problem is that waitFor will never poll since the setTimeout/setInterval has been mocked.

    Hopefully this provides the information you are looking for.

  15. mpeyper commented on Jun 21, 2021

    @mpeyper
    Member

    Yep, that makes sense to me.

    Just to clarify, no amount of running pending timers or advancing them before the waitFor will make it pass because the timeout hasn't been created yet, right?

    What if the run/advance was in the waitFor callback?

  16. 21 remaining items

  17. mpeyper commented on Jun 3, 2022

    @mpeyper
    Member

    The implementation in the alpha branch has some issues and I never found time to get to the bottom of it. It’s unlikely we’ll ever merge that into the main branch now.

    For what it’s worth, the new RTL version already supports fake timers. I’m not sure about the new RNTL version though.

  18. enzoferey commented on Jul 24, 2022

    @enzoferey

    Very good pointer @joeythomaschaske 🎯

    Indeed, waitFor uses setInterval, so if you use jest.useFakeTimers({ doNotFake: ["setInterval"] }) as you suggested it works.

    For Vitest users, the API is a bit better as you can directly specify the only thing you want to fake. For example: vi.useFakeTimers({ toFake: ["setTimeout"] }).

  19. sajTempler commented on Jul 27, 2022

    @sajTempler

    I wanted only Date to be faked actually (while allowing all promises and intervals) hence I had to list implicitly other things as well:

    jest
    .useFakeTimers({
      doNotFake: [
        'setImmediate',
        'setInterval',
        'setTimeout',
        'cancelAnimationFrame',
        'cancelIdleCallback',
        'clearImmediate',
        'clearInterval',
        'clearTimeout',
        'nextTick',
        'queueMicrotask',
      ],
    })
    .setSystemTime(new Date('2022-07-31'));
    
  20. tim-phillips commented on Apr 21, 2023

    @tim-phillips

    Just had to update RTL, which resolved it for me.

  21. seanzer commented on Jun 22, 2023

    @seanzer

    I've been using this solution, but depending on what you want it might not be all that useful

    async function waitFor(cb) {
      let success = false;
      do {
        try {
          success = cb();
        } catch {}
        jest.runOnlyPendingTimers();
        await Promise.resolve();
      } while (!success);
    }
  22. adbutterfield commented on Jun 26, 2023

    @adbutterfield

    Thanks @enzoferey!!!
    I was struggling with this problem migrating tests to vite for a few hours...
    vi.useFakeTimers({ toFake: ['Date'], now: new Date(2022, 2, 20, 8, 0, 0) });
    Works like a charm!

  23. flakey-bit commented on Sep 22, 2023

    @flakey-bit

    As a workaround, you can switch back to using real timers immediately before invoking waitFor()

    e.g.

    // Arrange
    jest.useFakeTimers();
    
    // Act
    doStuffThatTakesALongTime();
    
    await jest.advanceTimersByTimeAsync(MAX_EXPECTED_TIME); // Fast forward
    
    // Assert
    jest.useRealTimers(); // Switch back to real timers so that we can use waitFor()
    await waitFor(() => expect(inputControl).toBeEnabled()); 
  24. gil-viz commented on Oct 26, 2023

    @gil-viz

    @flakey-bit approach worked for me even without the jest.advanceTimersByTimeAsync, amazing, thanks!

  25. jcready commented on Nov 30, 2023

    @jcready

    The implementation in the alpha branch has some issues and I never found time to get to the bottom of it. It’s unlikely we’ll ever merge that into the main branch now.

    This is a bit disappointing. Especially since the changelog between 8.0.0-alpha.1 and 8.0.0 did not mention that this was effectively removed from the v8 major version. We just spent time upgrading from v7 to v8 for the sole purpose of getting this fix just to find out that it's not there.

    For what it’s worth, the new RTL version already supports fake timers.

    I don't see how this is relevant. The new RTL versions all require upgrading to react v18 which is no small ask.

  26. mpeyper commented on Nov 30, 2023

    @mpeyper
    Member

    My apologies @jcready for the waste of your time.

    This library has been effectively deprecated for quite some time now.

    While I understand upgrading to React 18 is no small feat, I do feel like it was a relevant thing for me to point out as many of my users would be looking to make that upgrade and along with it would likely need to migrate away from this library anyway. After all, React 18 has been out now for almost 2 years now.

    All that being said, I’ll update the release notes to mention that it was not included to hopefully save someone else from wasting their time also.

  27. jcready commented on Nov 30, 2023

    @jcready

    This library has been effectively deprecated for quite some time now.

    I'm not sure if you've actually read through that issue thread, but on top of the major react 18 changes it sounds like we'd have to switch to an utterly crippled version of renderHook.

    After all, React 18 has been out now for almost 2 years now.

    React 18 is the Python 3 of version changes.

  28. mpeyper commented on Nov 30, 2023

    @mpeyper
    Member

    Oh, I definitely had opinions about the changes, but ultimately I was not prepared to continue supporting an offshoot of functionality from the main RTL version which would largely serve as a source of confusion to many users.

    Admittedly, I don’t think we have done a good enough job in actually deprecating this library and thats largely been due to changes in my life distracting me (I don’t work with react or even JavaScript anymore) and the burnout I was feeling (largely caused by the thread I linked above) in actually supporting a dying library.

    I suggest if the new version is missing features that you use, and there is a good use case for them, raise an issue in their repo to add support for it.

  29. VirtuaBoza commented on Apr 23, 2025

    @VirtuaBoza

    If you came here due to issues using vitest's useFakeTimers, try this:

    global.jest = vi;

    Internally, waitFor checks if you're using jest (but not vitest) and then checks if you're using useFakeTimers. This allows the check to respect vitest's useFakeTimers as well.

  30. joeythomaschaske commented on Apr 23, 2025

    @joeythomaschaske

    If you came here due to issues using vitest's useFakeTimers, try this:

    global.jest = vi;
    Internally, waitFor checks if you're using jest (but not vitest) and then checks if you're using useFakeTimers. This allows the check to respect vitest's useFakeTimers as well.

    Wholesale replacing jest with vi seems like it could cause more issues down the road

  31. VirtuaBoza commented on Apr 23, 2025

    @VirtuaBoza

    If you came here due to issues using vitest's useFakeTimers, try this:

    global.jest = vi;
    Internally, waitFor checks if you're using jest (but not vitest) and then checks if you're using useFakeTimers. This allows the check to respect vitest's useFakeTimers as well.

    Wholesale replacing jest with vi seems like it could cause more issues down the road

    delete global.jest after the test. Easy peasy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugreleased on @alpha

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions