Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(waitFor): Automatically advance Jest fake timers #878

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
57 changes: 38 additions & 19 deletions src/__tests__/asyncHook.fakeTimers.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as React from 'react'

describe('async hook (fake timers) tests', () => {
beforeEach(() => {
jest.useFakeTimers()
Expand All @@ -20,8 +22,6 @@ describe('async hook (fake timers) tests', () => {

let complete = false

jest.advanceTimersByTime(200)

await waitFor(() => {
expect(actual).toBe(expected)
complete = true
Expand All @@ -30,26 +30,45 @@ describe('async hook (fake timers) tests', () => {
expect(complete).toBe(true)
})

test('should wait for arbitrary expectation to pass when using runOnlyPendingTimers()', async () => {
const { waitFor } = renderHook(() => null)

let actual = 0
const expected = 1

setTimeout(() => {
actual = expected
}, 200)

let complete = false

jest.runOnlyPendingTimers()
test('it waits for the data to be loaded using', async () => {
const fetchAMessage = () =>
new Promise((resolve) => {
// we are using random timeout here to simulate a real-time example
// of an async operation calling a callback at a non-deterministic time
const randomTimeout = Math.floor(Math.random() * 100)
setTimeout(() => {
resolve({ returnedMessage: 'Hello World' })
}, randomTimeout)
})

function useLoader() {
const [state, setState] = React.useState<{ data: unknown; loading: boolean }>({
data: undefined,
loading: true
})
React.useEffect(() => {
let cancelled = false
fetchAMessage().then((data) => {
if (!cancelled) {
setState({ data, loading: false })
}
})

return () => {
cancelled = true
}
}, [])

return state
}

const { result, waitFor } = renderHook(() => useLoader())

expect(result.current).toEqual({ data: undefined, loading: true })

await waitFor(() => {
expect(actual).toBe(expected)
complete = true
expect(result.current).toEqual({ data: { returnedMessage: 'Hello World' }, loading: false })
})

expect(complete).toBe(true)
})
})
})
Expand Down
131 changes: 131 additions & 0 deletions src/core/asyncUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,27 @@ import { TimeoutError } from '../helpers/error'
const DEFAULT_INTERVAL = 50
const DEFAULT_TIMEOUT = 1000

// This is so the stack trace the developer sees is one that's
// closer to their code (because async stack traces are hard to follow).
function copyStackTrace(target: Error, source: Error) {
target.stack = source.stack?.replace(source.message, target.message)
}

function jestFakeTimersAreEnabled() {
/* istanbul ignore else */
if (typeof jest !== 'undefined' && jest !== null) {
return (
// legacy timers
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(setTimeout as any)._isMockFunction === true ||
// modern timers
Object.prototype.hasOwnProperty.call(setTimeout, 'clock')
)
}
// istanbul ignore next
return false
}

function asyncUtils(act: Act, addResolver: (callback: () => void) => void): AsyncUtils {
const wait = async (callback: () => boolean | void, { interval, timeout }: WaitOptions) => {
const checkResult = () => {
Expand Down Expand Up @@ -42,6 +63,107 @@ function asyncUtils(act: Act, addResolver: (callback: () => void) => void): Asyn
return !timeoutSignal.timedOut
}

/**
* `waitFor` implementation from `@testing-library/dom` for Jest fake timers
* @param callback
* @param param1
* @returns
*/
const waitForInJestFakeTimers = (
callback: () => boolean | void,
{
interval,
stackTraceError,
timeout
}: { interval: number; timeout: number; stackTraceError: Error }
) => {
return new Promise(async (resolve, reject) => {
let lastError: unknown
let finished = false

const overallTimeoutTimer = setTimeout(handleTimeout, timeout)

checkCallback()
// this is a dangerous rule to disable because it could lead to an
// infinite loop. However, eslint isn't smart enough to know that we're
// setting finished inside `onDone` which will be called when we're done
// waiting or when we've timed out.
// eslint-disable-next-line no-unmodified-loop-condition
while (!finished) {
if (!jestFakeTimersAreEnabled()) {
const error = 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`
)
copyStackTrace(error, stackTraceError)
reject(error)
return
}
// we *could* (maybe should?) use `advanceTimersToNextTimer` but it's
// possible that could make this loop go on forever if someone is using
// third party code that's setting up recursive timers so rapidly that
// the user's timer's don't get a chance to resolve. So we'll advance
// by an interval instead. (We have a test for this case).
jest.advanceTimersByTime(interval)

// It's really important that checkCallback is run *before* we flush
// in-flight promises. To be honest, I'm not sure why, and I can't quite
// think of a way to reproduce the problem in a test, but I spent
// an entire day banging my head against a wall on this.
checkCallback()

if (finished) {
break
}

// In this rare case, we *need* to wait for in-flight promises
// to resolve before continuing. We don't need to take advantage
// of parallelization so we're fine.
// https://stackoverflow.com/a/59243586/971592
await act(async () => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is useless for React 17 and should be removed to not confuse. It is only needed in 18 where we need to remove the act from waitFor

await new Promise((r) => {
setTimeout(r, 0)
jest.advanceTimersByTime(0)
})
})
}

function onDone(error: unknown, result: boolean | void | null) {
finished = true
clearTimeout(overallTimeoutTimer)

if (error) {
reject(error)
} else {
resolve(result)
}
}

function checkCallback() {
try {
const result = callback()

onDone(null, result)

// If `callback` throws, wait for the next mutation, interval, or timeout.
} catch (error: unknown) {
// Save the most recent callback error to reject the promise with it in the event of a timeout
lastError = error
}
}

function handleTimeout() {
let error
if (lastError) {
error = lastError
} else {
error = new Error('Timed out in waitFor.')
copyStackTrace(error, stackTraceError)
}
onDone(error, null)
}
})
}

const waitFor = async (
callback: () => boolean | void,
{ interval = DEFAULT_INTERVAL, timeout = DEFAULT_TIMEOUT }: WaitForOptions = {}
Expand All @@ -54,6 +176,15 @@ function asyncUtils(act: Act, addResolver: (callback: () => void) => void): Asyn
}
}

if (typeof interval === 'number' && typeof timeout === 'number' && jestFakeTimersAreEnabled()) {
// create the error here so its stack trace is as close to the
// calling code as possible
const stackTraceError = new Error('STACK_TRACE_MESSAGE')
return act(async () => {
await waitForInJestFakeTimers(callback, { interval, stackTraceError, timeout })
})
}

const result = await wait(safeCallback, { interval, timeout })
if (!result && timeout) {
throw new TimeoutError(waitFor, timeout)
Expand Down