Skip to content

Commit 0d6e95a

Browse files
committed
Add more tests around cleanup with fake timers
1 parent 5a10621 commit 0d6e95a

File tree

1 file changed

+82
-1
lines changed

1 file changed

+82
-1
lines changed

src/__tests__/cleanup.js

+82-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import React from 'react'
2-
import {render, cleanup} from '../'
2+
import {render, cleanup, act} from '../'
33

44
test('cleans up the document', async () => {
55
const spy = jest.fn()
@@ -40,3 +40,84 @@ test('cleanup runs effect cleanup functions', async () => {
4040
await cleanup()
4141
expect(spy).toHaveBeenCalledTimes(1)
4242
})
43+
44+
describe('fake timers and missing act warnings', () => {
45+
beforeEach(() => {
46+
jest.resetAllMocks()
47+
jest.spyOn(console, 'error').mockImplementation(() => {
48+
// assert messages aexplicitly
49+
})
50+
jest.useFakeTimers()
51+
})
52+
53+
afterEach(() => {
54+
jest.useRealTimers()
55+
})
56+
57+
test('cleanup does not flush immediates', async () => {
58+
const microTaskSpy = jest.fn()
59+
function Test() {
60+
const counter = 1
61+
const [, setDeferredCounter] = React.useState(null)
62+
React.useEffect(() => {
63+
let cancelled = false
64+
setImmediate(() => {
65+
microTaskSpy()
66+
if (!cancelled) {
67+
setDeferredCounter(counter)
68+
}
69+
})
70+
71+
return () => {
72+
cancelled = true
73+
}
74+
}, [counter])
75+
76+
return null
77+
}
78+
render(<Test />)
79+
80+
await cleanup()
81+
82+
expect(microTaskSpy).toHaveBeenCalledTimes(0)
83+
// console.error is mocked
84+
// eslint-disable-next-line no-console
85+
expect(console.error).toHaveBeenCalledTimes(0)
86+
})
87+
88+
test('cleanup does not swallow missing act warnings', async () => {
89+
const deferredStateUpdateSpy = jest.fn()
90+
function Test() {
91+
const counter = 1
92+
const [, setDeferredCounter] = React.useState(null)
93+
React.useEffect(() => {
94+
let cancelled = false
95+
setImmediate(() => {
96+
deferredStateUpdateSpy()
97+
if (!cancelled) {
98+
setDeferredCounter(counter)
99+
}
100+
})
101+
102+
return () => {
103+
cancelled = true
104+
}
105+
}, [counter])
106+
107+
return null
108+
}
109+
render(<Test />)
110+
111+
jest.runAllImmediates()
112+
await cleanup()
113+
114+
expect(deferredStateUpdateSpy).toHaveBeenCalledTimes(1)
115+
// console.error is mocked
116+
// eslint-disable-next-line no-console
117+
expect(console.error).toHaveBeenCalledTimes(1)
118+
// eslint-disable-next-line no-console
119+
expect(console.error.mock.calls[0][0]).toMatch(
120+
'a test was not wrapped in act(...)',
121+
)
122+
})
123+
})

0 commit comments

Comments
 (0)