Skip to content

Commit

Permalink
Add support for testing updates granularly
Browse files Browse the repository at this point in the history
  • Loading branch information
Sebastian Silbermann committed Oct 5, 2023
1 parent d78b532 commit f676301
Show file tree
Hide file tree
Showing 10 changed files with 283 additions and 140 deletions.
99 changes: 99 additions & 0 deletions src/__tests__/act-compat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import * as React from 'react'
import {render, fireEvent, screen} from '../'
import {actIfEnabled} from '../act-compat'

beforeEach(() => {
global.IS_REACT_ACT_ENVIRONMENT = true
})

test('render calls useEffect immediately', async () => {
const effectCb = jest.fn()
function MyUselessComponent() {
React.useEffect(effectCb)
return null
}
await render(<MyUselessComponent />)
expect(effectCb).toHaveBeenCalledTimes(1)
})

test('findByTestId returns the element', async () => {
const ref = React.createRef()
await render(<div ref={ref} data-testid="foo" />)
expect(await screen.findByTestId('foo')).toBe(ref.current)
})

test('fireEvent triggers useEffect calls', async () => {
const effectCb = jest.fn()
function Counter() {
React.useEffect(effectCb)
const [count, setCount] = React.useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}
const {
container: {firstChild: buttonNode},
} = await render(<Counter />)

effectCb.mockClear()
// eslint-disable-next-line testing-library/no-await-sync-events -- TODO: Remove lint rule.
await fireEvent.click(buttonNode)
expect(buttonNode).toHaveTextContent('1')
expect(effectCb).toHaveBeenCalledTimes(1)
})

test('calls to hydrate will run useEffects', async () => {
const effectCb = jest.fn()
function MyUselessComponent() {
React.useEffect(effectCb)
return null
}
await render(<MyUselessComponent />, {hydrate: true})
expect(effectCb).toHaveBeenCalledTimes(1)
})

test('cleans up IS_REACT_ACT_ENVIRONMENT if its callback throws', async () => {
global.IS_REACT_ACT_ENVIRONMENT = false

await expect(() =>
actIfEnabled(() => {
throw new Error('threw')
}),
).rejects.toThrow('threw')

expect(global.IS_REACT_ACT_ENVIRONMENT).toEqual(false)
})

test('cleans up IS_REACT_ACT_ENVIRONMENT if its async callback throws', async () => {
global.IS_REACT_ACT_ENVIRONMENT = false

await expect(() =>
actIfEnabled(async () => {
throw new Error('thenable threw')
}),
).rejects.toThrow('thenable threw')

expect(global.IS_REACT_ACT_ENVIRONMENT).toEqual(false)
})

test('state update from microtask does not trigger "missing act" warning', async () => {
let triggerStateUpdateFromMicrotask
function App() {
const [state, setState] = React.useState(0)
triggerStateUpdateFromMicrotask = () => setState(1)
React.useEffect(() => {
// eslint-disable-next-line jest/no-conditional-in-test
if (state === 1) {
Promise.resolve().then(() => {
setState(2)
})
}
}, [state])
return state
}
const {container} = await render(<App />)

await actIfEnabled(() => {
triggerStateUpdateFromMicrotask()
})

expect(container).toHaveTextContent('2')
})
104 changes: 16 additions & 88 deletions src/__tests__/act.js
Original file line number Diff line number Diff line change
@@ -1,98 +1,26 @@
import * as React from 'react'
import {act, render, fireEvent, screen} from '../'
import {act, render} from '../'

beforeEach(() => {
global.IS_REACT_ACT_ENVIRONMENT = true
})

test('render calls useEffect immediately', async () => {
const effectCb = jest.fn()
function MyUselessComponent() {
React.useEffect(effectCb)
return null
}
await render(<MyUselessComponent />)
expect(effectCb).toHaveBeenCalledTimes(1)
})

test('findByTestId returns the element', async () => {
const ref = React.createRef()
await render(<div ref={ref} data-testid="foo" />)
expect(await screen.findByTestId('foo')).toBe(ref.current)
})

test('fireEvent triggers useEffect calls', async () => {
const effectCb = jest.fn()
function Counter() {
React.useEffect(effectCb)
const [count, setCount] = React.useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}
const {
container: {firstChild: buttonNode},
} = await render(<Counter />)

effectCb.mockClear()
// eslint-disable-next-line testing-library/no-await-sync-events -- TODO: Remove lint rule.
await fireEvent.click(buttonNode)
expect(buttonNode).toHaveTextContent('1')
expect(effectCb).toHaveBeenCalledTimes(1)
})

test('calls to hydrate will run useEffects', async () => {
const effectCb = jest.fn()
function MyUselessComponent() {
React.useEffect(effectCb)
return null
}
await render(<MyUselessComponent />, {hydrate: true})
expect(effectCb).toHaveBeenCalledTimes(1)
})

test('cleans up IS_REACT_ACT_ENVIRONMENT if its callback throws', async () => {
global.IS_REACT_ACT_ENVIRONMENT = false

await expect(() =>
act(() => {
throw new Error('threw')
}),
).rejects.toThrow('threw')

expect(global.IS_REACT_ACT_ENVIRONMENT).toEqual(false)
})

test('cleans up IS_REACT_ACT_ENVIRONMENT if its async callback throws', async () => {
global.IS_REACT_ACT_ENVIRONMENT = false

await expect(() =>
act(async () => {
throw new Error('thenable threw')
}),
).rejects.toThrow('thenable threw')

expect(global.IS_REACT_ACT_ENVIRONMENT).toEqual(false)
})

test('state update from microtask does not trigger "missing act" warning', async () => {
let triggerStateUpdateFromMicrotask
function App() {
const [state, setState] = React.useState(0)
triggerStateUpdateFromMicrotask = () => setState(1)
React.useEffect(() => {
// eslint-disable-next-line jest/no-conditional-in-test
if (state === 1) {
Promise.resolve().then(() => {
setState(2)
})
}
}, [state])
test('does not work outside IS_REACT_ENVIRONMENT like React.act', async () => {
let setState
function Component() {
const [state, _setState] = React.useState(0)
setState = _setState
return state
}
const {container} = await render(<App />)

await act(() => {
triggerStateUpdateFromMicrotask()
})
await render(<Component />)

expect(container).toHaveTextContent('2')
global.IS_REACT_ACT_ENVIRONMENT = false
await expect(async () => {
await act(() => {
setState(1)
})
}).toErrorDev(
'Warning: The current testing environment is not configured to support act(...)',
{withoutStack: true},
)
})
1 change: 1 addition & 0 deletions src/__tests__/auto-cleanup-skip.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as React from 'react'
let render
beforeAll(() => {
process.env.RTL_SKIP_AUTO_CLEANUP = 'true'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const rtl = require('../')
render = rtl.render
})
Expand Down
129 changes: 124 additions & 5 deletions src/__tests__/end-to-end.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as React from 'react'
import {render, waitForElementToBeRemoved, screen, waitFor} from '../'
let React, cleanup, render, screen, waitFor, waitForElementToBeRemoved

describe.each([
['real timers', () => jest.useRealTimers()],
Expand All @@ -9,10 +8,25 @@ describe.each([
'it waits for the data to be loaded in a macrotask using %s',
(label, useTimers) => {
beforeEach(() => {
jest.resetModules()
global.IS_REACT_ACT_ENVIRONMENT = true
process.env.RTL_SKIP_AUTO_CLEANUP = '0'

useTimers()

React = require('react')
;({
cleanup,
render,
screen,
waitFor,
waitForElementToBeRemoved,
} = require('..'))
})

afterEach(() => {
afterEach(async () => {
await cleanup()
global.IS_REACT_ACT_ENVIRONMENT = false
jest.useRealTimers()
})

Expand Down Expand Up @@ -83,10 +97,25 @@ describe.each([
'it waits for the data to be loaded in many microtask using %s',
(label, useTimers) => {
beforeEach(() => {
jest.resetModules()
global.IS_REACT_ACT_ENVIRONMENT = true
process.env.RTL_SKIP_AUTO_CLEANUP = '0'

useTimers()

React = require('react')
;({
cleanup,
render,
screen,
waitFor,
waitForElementToBeRemoved,
} = require('..'))
})

afterEach(() => {
afterEach(async () => {
await cleanup()
global.IS_REACT_ACT_ENVIRONMENT = false
jest.useRealTimers()
})

Expand Down Expand Up @@ -167,10 +196,25 @@ describe.each([
'it waits for the data to be loaded in a microtask using %s',
(label, useTimers) => {
beforeEach(() => {
jest.resetModules()
global.IS_REACT_ACT_ENVIRONMENT = true
process.env.RTL_SKIP_AUTO_CLEANUP = '0'

useTimers()

React = require('react')
;({
cleanup,
render,
screen,
waitFor,
waitForElementToBeRemoved,
} = require('..'))
})

afterEach(() => {
afterEach(async () => {
await cleanup()
global.IS_REACT_ACT_ENVIRONMENT = false
jest.useRealTimers()
})

Expand Down Expand Up @@ -218,3 +262,78 @@ describe.each([
})
},
)

describe.each([
['real timers', () => jest.useRealTimers()],
['fake legacy timers', () => jest.useFakeTimers('legacy')],
['fake modern timers', () => jest.useFakeTimers('modern')],
])('testing intermediate states using %s', (label, useTimers) => {
beforeEach(() => {
jest.resetModules()
global.IS_REACT_ACT_ENVIRONMENT = false
process.env.RTL_SKIP_AUTO_CLEANUP = '0'

useTimers()

React = require('react')
;({render, screen, waitFor, waitForElementToBeRemoved} = require('..'))
})

afterEach(async () => {
await cleanup()
jest.useRealTimers()
global.IS_REACT_ACT_ENVIRONMENT = true
})

const fetchAMessageInAMicrotask = () =>
Promise.resolve({
status: 200,
json: () => Promise.resolve({title: 'Hello World'}),
})

function ComponentWithMicrotaskLoader() {
const [fetchState, setFetchState] = React.useState({fetching: true})

React.useEffect(() => {
if (fetchState.fetching) {
fetchAMessageInAMicrotask().then(res => {
return res.json().then(data => {
setFetchState({todo: data.title, fetching: false})
})
})
}
}, [fetchState])

if (fetchState.fetching) {
return <p>Loading..</p>
}

return (
<div data-testid="message">Loaded this message: {fetchState.todo}</div>
)
}

test('waitFor', async () => {
await render(<ComponentWithMicrotaskLoader />)

await waitFor(() => {
expect(screen.getByText('Loading..')).toBeInTheDocument()
})

await waitFor(() => {
expect(screen.getByText(/Loaded this message:/)).toBeInTheDocument()
})

expect(screen.getByTestId('message')).toHaveTextContent(/Hello World/)
})

test('findBy', async () => {
await render(<ComponentWithMicrotaskLoader />)

await screen.findByText('Loading..')

await screen.findByText(/Loaded this message:/)

expect(screen.getByTestId('message')).toHaveTextContent(/Hello World/)
})
})
Loading

0 comments on commit f676301

Please sign in to comment.