Skip to content

Commit 2632aae

Browse files
committed
Add assertions for real and fake runtime
1 parent ab64018 commit 2632aae

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/__tests__/fake-timers.js

+13-2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ async function runWaitFor({time = 300} = {}, options) {
1111
await waitFor(() => expect(result).toBe(response), options)
1212
}
1313

14+
afterEach(() => {
15+
jest.useRealTimers()
16+
})
17+
1418
test('real timers', async () => {
1519
// the only difference when not using fake timers is this test will
1620
// have to wait the full length of the timeout
@@ -40,9 +44,10 @@ test('fake timer timeout', async () => {
4044
})
4145

4246
test('times out after 1000ms by default', async () => {
47+
const startReal = performance.now()
4348
jest.useFakeTimers()
4449
const {container} = render(`<div></div>`)
45-
const start = performance.now()
50+
const startFake = performance.now()
4651
// there's a bug with this rule here...
4752
// eslint-disable-next-line jest/valid-expect
4853
await expect(
@@ -51,7 +56,13 @@ test('times out after 1000ms by default', async () => {
5156
`Timed out in waitForElementToBeRemoved.`,
5257
)
5358
// NOTE: this assertion ensures that the timeout runs in the declared (fake) clock.
54-
expect(performance.now() - start).toBeGreaterThanOrEqual(1000)
59+
expect(performance.now() - startFake).toBeGreaterThanOrEqual(1000)
60+
jest.useRealTimers()
61+
// NOTE: this assertion ensures that the timeout runs in the declared (fake) clock
62+
// while in real time the time was only a fraction since the real clock is only bound by the CPU.
63+
// So 20ms is really just an approximation on how long the CPU needs to execute our code.
64+
// If people want to timeout in real time they should rely on their test runners.
65+
expect(performance.now() - startReal).toBeLessThanOrEqual(20)
5566
})
5667

5768
test('recursive timers do not cause issues', async () => {

0 commit comments

Comments
 (0)