From 84851dc660d49543707ba9eead42395c45ec06e2 Mon Sep 17 00:00:00 2001 From: Sebastian Silbermann Date: Sun, 12 Sep 2021 11:12:06 +0200 Subject: [PATCH] test: Backport tests using the full timer matrix (#962) --- src/__tests__/end-to-end.js | 76 +++++++++++++++++++++++++++---------- 1 file changed, 56 insertions(+), 20 deletions(-) diff --git a/src/__tests__/end-to-end.js b/src/__tests__/end-to-end.js index 87c70f1b..cf222aec 100644 --- a/src/__tests__/end-to-end.js +++ b/src/__tests__/end-to-end.js @@ -1,5 +1,5 @@ import * as React from 'react' -import {render, waitForElementToBeRemoved, screen} from '../' +import {render, waitForElementToBeRemoved, screen, waitFor} from '../' const fetchAMessage = () => new Promise(resolve => { @@ -11,27 +11,63 @@ const fetchAMessage = () => }, randomTimeout) }) -class ComponentWithLoader extends React.Component { - state = {loading: true} - async componentDidMount() { - const data = await fetchAMessage() - this.setState({data, loading: false}) // eslint-disable-line - } - render() { - if (this.state.loading) { - return
Loading...
+function ComponentWithLoader() { + const [state, setState] = React.useState({data: undefined, loading: true}) + React.useEffect(() => { + let cancelled = false + fetchAMessage().then(data => { + if (!cancelled) { + setState({data, loading: false}) + } + }) + + return () => { + cancelled = true } - return ( -
- Loaded this message: {this.state.data.returnedMessage}! -
- ) + }, []) + + if (state.loading) { + return
Loading...
} + + return ( +
+ Loaded this message: {state.data.returnedMessage}! +
+ ) } -test('it waits for the data to be loaded', async () => { - render() - const loading = () => screen.getByText('Loading...') - await waitForElementToBeRemoved(loading) - expect(screen.getByTestId('message')).toHaveTextContent(/Hello World/) +describe.each([ + ['real timers', () => jest.useRealTimers()], + ['fake legacy timers', () => jest.useFakeTimers('legacy')], + ['fake modern timers', () => jest.useFakeTimers('modern')], +])('it waits for the data to be loaded using %s', (label, useTimers) => { + beforeEach(() => { + useTimers() + }) + + afterEach(() => { + jest.useRealTimers() + }) + + test('waitForElementToBeRemoved', async () => { + render() + const loading = () => screen.getByText('Loading...') + await waitForElementToBeRemoved(loading) + expect(screen.getByTestId('message')).toHaveTextContent(/Hello World/) + }) + + test('waitFor', async () => { + render() + const message = () => screen.getByText(/Loaded this message:/) + await waitFor(message) + expect(screen.getByTestId('message')).toHaveTextContent(/Hello World/) + }) + + test('findBy', async () => { + render() + await expect(screen.findByTestId('message')).resolves.toHaveTextContent( + /Hello World/, + ) + }) })