Skip to content

Commit

Permalink
test: Backport tests using the full timer matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed Sep 12, 2021
1 parent 3325061 commit b6ce4fa
Showing 1 changed file with 56 additions and 20 deletions.
76 changes: 56 additions & 20 deletions 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 => {
Expand All @@ -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 <div>Loading...</div>
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 (
<div data-testid="message">
Loaded this message: {this.state.data.returnedMessage}!
</div>
)
}, [])

if (state.loading) {
return <div>Loading...</div>
}

return (
<div data-testid="message">
Loaded this message: {state.data.returnedMessage}!
</div>
)
}

test('it waits for the data to be loaded', async () => {
render(<ComponentWithLoader />)
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(<ComponentWithLoader />)
const loading = () => screen.getByText('Loading...')
await waitForElementToBeRemoved(loading)
expect(screen.getByTestId('message')).toHaveTextContent(/Hello World/)
})

test('waitFor', async () => {
render(<ComponentWithLoader />)
const message = () => screen.getByText(/Loaded this message:/)
await waitFor(message)
expect(screen.getByTestId('message')).toHaveTextContent(/Hello World/)
})

test('findBy', async () => {
render(<ComponentWithLoader />)
await expect(screen.findByTestId('message')).resolves.toHaveTextContent(
/Hello World/,
)
})
})

0 comments on commit b6ce4fa

Please sign in to comment.