Skip to content

Commit 6b4180e

Browse files
authored
test: Add test for flushing before exiting waitFor (#1215)
1 parent 5dc81dc commit 6b4180e

File tree

1 file changed

+71
-1
lines changed

1 file changed

+71
-1
lines changed

src/__tests__/end-to-end.js

+71-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ describe.each([
8080
['fake legacy timers', () => jest.useFakeTimers('legacy')],
8181
['fake modern timers', () => jest.useFakeTimers('modern')],
8282
])(
83-
'it waits for the data to be loaded in a microtask using %s',
83+
'it waits for the data to be loaded in many microtask using %s',
8484
(label, useTimers) => {
8585
beforeEach(() => {
8686
useTimers()
@@ -162,3 +162,73 @@ describe.each([
162162
})
163163
},
164164
)
165+
166+
describe.each([
167+
['real timers', () => jest.useRealTimers()],
168+
['fake legacy timers', () => jest.useFakeTimers('legacy')],
169+
['fake modern timers', () => jest.useFakeTimers('modern')],
170+
])(
171+
'it waits for the data to be loaded in a microtask using %s',
172+
(label, useTimers) => {
173+
beforeEach(() => {
174+
useTimers()
175+
})
176+
177+
afterEach(() => {
178+
jest.useRealTimers()
179+
})
180+
181+
const fetchAMessageInAMicrotask = () =>
182+
Promise.resolve({
183+
status: 200,
184+
json: () => Promise.resolve({title: 'Hello World'}),
185+
})
186+
187+
function ComponentWithMicrotaskLoader() {
188+
const [fetchState, setFetchState] = React.useState({fetching: true})
189+
190+
React.useEffect(() => {
191+
if (fetchState.fetching) {
192+
fetchAMessageInAMicrotask().then(res => {
193+
return res.json().then(data => {
194+
setFetchState({todo: data.title, fetching: false})
195+
})
196+
})
197+
}
198+
}, [fetchState])
199+
200+
if (fetchState.fetching) {
201+
return <p>Loading..</p>
202+
}
203+
204+
return (
205+
<div data-testid="message">Loaded this message: {fetchState.todo}</div>
206+
)
207+
}
208+
209+
test('waitForElementToBeRemoved', async () => {
210+
render(<ComponentWithMicrotaskLoader />)
211+
const loading = () => screen.getByText('Loading..')
212+
await waitForElementToBeRemoved(loading)
213+
expect(screen.getByTestId('message')).toHaveTextContent(/Hello World/)
214+
})
215+
216+
test('waitFor', async () => {
217+
render(<ComponentWithMicrotaskLoader />)
218+
await waitFor(() => {
219+
screen.getByText('Loading..')
220+
})
221+
await waitFor(() => {
222+
screen.getByText(/Loaded this message:/)
223+
})
224+
expect(screen.getByTestId('message')).toHaveTextContent(/Hello World/)
225+
})
226+
227+
test('findBy', async () => {
228+
render(<ComponentWithMicrotaskLoader />)
229+
await expect(screen.findByTestId('message')).resolves.toHaveTextContent(
230+
/Hello World/,
231+
)
232+
})
233+
},
234+
)

0 commit comments

Comments
 (0)