Skip to content

Commit 95504af

Browse files
committed
This PR:
- awaits an `act(async () => {})` inside `cleanup-after-each` Some possible Q&A: - why not do the same in sync cleanup()?: if peeps are using react-testing-library already, it's suuuper unlikely they'll have hanging sync effects/updates. Decided not to add code without a good reason. (bonus: fixes a lint violation in act-compat.js)
1 parent 4c8ca23 commit 95504af

File tree

4 files changed

+46
-2
lines changed

4 files changed

+46
-2
lines changed

cleanup-after-each.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
1-
afterEach(require('./dist').cleanup)
1+
afterEach(() => {
2+
return require('./dist/cleanup-async')()
3+
})

src/__tests__/cleanup-after-each.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import React from 'react'
2+
import {render} from '../index'
3+
import cleanupAsync from '../cleanup-async'
4+
5+
afterEach(() => {
6+
return cleanupAsync()
7+
})
8+
9+
const log = []
10+
let ctr = 0
11+
12+
function App() {
13+
async function somethingAsync() {
14+
await null
15+
log.push(ctr++)
16+
}
17+
React.useEffect(() => {
18+
somethingAsync()
19+
}, [])
20+
return 123
21+
}
22+
23+
it('cleanup-after-each does not leave any hanging microtasks: part 1', () => {
24+
render(<App />)
25+
expect(document.body.textContent).toBe('123')
26+
expect(log).toEqual([])
27+
})
28+
29+
it('cleanup-after-each does not leave any hanging microtasks: part 2', () => {
30+
expect(log).toEqual([0])
31+
expect(document.body.innerHTML).toBe('')
32+
})

src/act-compat.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import React from 'react'
22
import ReactDOM from 'react-dom'
3-
import {reactDomSixteenPointNineIsReleased} from './react-dom-16.9.0-is-released'
43
import * as testUtils from 'react-dom/test-utils'
4+
import {reactDomSixteenPointNineIsReleased} from './react-dom-16.9.0-is-released'
55

66
const reactAct = testUtils.act
77
const actSupported = reactAct !== undefined

src/cleanup-async.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// This file is for use by the top-level export
2+
// @testing-library/react/cleanup-after-each
3+
// It is not meant to be used directly
4+
5+
module.exports = async function cleanupAsync() {
6+
const {asyncAct} = require('./act-compat')
7+
const {cleanup} = require('./index')
8+
await asyncAct(async () => {})
9+
cleanup()
10+
}

0 commit comments

Comments
 (0)