Repository navigation
Description
react-hooks-testing-libraryversion: 7.0.0reactversion: 17.0.2react-domversion: 17.0.2nodeversion: 14.16.0npmversion: 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
mpeyper commentedon May 28, 2021
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
waitForis 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.
chris110408 commentedon Jun 8, 2021
@mpeyper
I would like to contribute, I think the outline for this solution will be a similar solution used by
dom-testing-libraryfor this step, I have a question, should we use their helper or we need helps by ourselves for the jestFakeTimersAreEnabled function and the setImmediateFn
mpeyper commentedon Jun 9, 2021
Sorry for the delay in responding @chris110408. Any contributions towards this are very welcome.
I think taking a similar approach to
dom-testing-libraryis 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 😉.chris110408 commentedon Jun 9, 2021
Thanks @mpeyper I will work on the PR
chris110408 commentedon Jun 15, 2021
I have been trying to find the fix for a typescript error.

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
mpeyper commentedon Jun 15, 2021
Give this a shot:
Object.entriesreturns[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 ofglobalObj.Hope this helps.
chris110408 commentedon Jun 15, 2021
It works
Thanks a lot for the explanation
chris110408 commentedon Jun 18, 2021
@mpeyper
I has been working on this issue recently,
I changed the fackerTimer detection code to this
However, I have a hard time to understand the issue,
this test will never pass no matter we use useFakeTimers or not.
and I change the test code to
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() ?
mpeyper commentedon Jun 18, 2021
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
advanceTimersByTimeis going to advance the internal timers as well, even as new timers are created for the different intervals, butrunOnlyPendingTimerswill only advance existing timers and the new ones never advance.@DennisSkoko is there more info you can provide to help @chris110408 out?
chris110408 commentedon Jun 18, 2021
@DennisSkoko @mpeyper
I add another test that uses the runOnlyPendingTimers and useFakeTimer and both test successfully pass
mpeyper commentedon Jun 18, 2021
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)
chris110408 commentedon Jun 21, 2021
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 forfunction of react-hooks-testing-library works in that way.DennisSkoko commentedon Jun 21, 2021
Hi @chris110408 @mpeyper, sorry for the late response.
From my point of view, what is happening is that the implementation of
waitForis using thesetTimeout/setIntervalwhich are mocked whenuseFakeTimersis used, resulting in the polling logic forwaitForwill just hang.I think the reason this works fine is that the
waitForwill never fail in this case. You are advancing time before invoking thewaitForwhich will result in the initial poll being successful. Here is hopefully a better example that showcases the problem:Here we can see that test cases fails with a Jest timeout. Reason being that
waitFordoes an initial poll that checks in the function does not throw, but in this case it will sincefalsedoes not equaltrue. As soon as the initial poll fromwaitForfails, thenwaitForwill usesetTimeout/setIntervalto poll. Now our problem is thatwaitForwill never poll since thesetTimeout/setIntervalhas been mocked.Hopefully this provides the information you are looking for.
mpeyper commentedon Jun 21, 2021
Yep, that makes sense to me.
Just to clarify, no amount of running pending timers or advancing them before the
waitForwill make it pass because the timeout hasn't been created yet, right?What if the run/advance was in the
waitForcallback?21 remaining items
mpeyper commentedon Jun 3, 2022
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.
enzoferey commentedon Jul 24, 2022
Very good pointer @joeythomaschaske 🎯
Indeed,
waitForusessetInterval, so if you usejest.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"] }).sajTempler commentedon Jul 27, 2022
I wanted only
Dateto be faked actually (while allowing all promises and intervals) hence I had to list implicitly other things as well:tim-phillips commentedon Apr 21, 2023
Just had to update RTL, which resolved it for me.
seanzer commentedon Jun 22, 2023
I've been using this solution, but depending on what you want it might not be all that useful
adbutterfield commentedon Jun 26, 2023
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!
flakey-bit commentedon Sep 22, 2023
As a workaround, you can switch back to using real timers immediately before invoking
waitFor()e.g.
gil-viz commentedon Oct 26, 2023
@flakey-bit approach worked for me even without the
jest.advanceTimersByTimeAsync, amazing, thanks!jcready commentedon Nov 30, 2023
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.
I don't see how this is relevant. The new RTL versions all require upgrading to react v18 which is no small ask.
mpeyper commentedon Nov 30, 2023
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.
jcready commentedon Nov 30, 2023
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.React 18 is the Python 3 of version changes.
mpeyper commentedon Nov 30, 2023
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.
VirtuaBoza commentedon Apr 23, 2025
If you came here due to issues using vitest's
useFakeTimers, try this:Internally,
waitForchecks if you're using jest (but not vitest) and then checks if you're usinguseFakeTimers. This allows the check to respect vitest'suseFakeTimersas well.joeythomaschaske commentedon Apr 23, 2025
Wholesale replacing jest with vi seems like it could cause more issues down the road
VirtuaBoza commentedon Apr 23, 2025
delete global.jestafter the test. Easy peasy.