Skip to content

Commit 31b8dfc

Browse files
author
Kent C. Dodds
committed
feat(cleanup): automatically cleanup if afterEach is detected
You can disable this with the RTL_SKIP_CLEANUP environment variable if you so choose, but it's recommended to have cleanup work this way. Closes #428
1 parent f77012e commit 31b8dfc

File tree

5 files changed

+42
-6
lines changed

5 files changed

+42
-6
lines changed

src/__tests__/auto-cleanup-skip.js

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import React from 'react'
2+
3+
let render
4+
beforeAll(() => {
5+
process.env.RTL_SKIP_CLEANUP = 'true'
6+
const rtl = require('../')
7+
render = rtl.render
8+
})
9+
10+
// This one verifies that if RTL_SKIP_CLEANUP is set
11+
// that we DON'T auto-wire up the afterEach for folks
12+
test('first', () => {
13+
render(<div>hi</div>)
14+
})
15+
16+
test('second', () => {
17+
expect(document.body.innerHTML).toEqual('<div><div>hi</div></div>')
18+
})

src/__tests__/auto-cleanup.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import React from 'react'
2+
import {render} from '../'
3+
4+
// This just verifies that by importing RTL in an
5+
// environment which supports afterEach (like jest)
6+
// we'll get automatic cleanup between tests.
7+
test('first', () => {
8+
render(<div>hi</div>)
9+
})
10+
11+
test('second', () => {
12+
expect(document.body.innerHTML).toEqual('')
13+
})

src/__tests__/cleanup-after-each.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import React from 'react'
2-
import {render} from '../index'
2+
import {render} from '../'
33
import cleanupAsync from '../cleanup-async'
44

55
afterEach(() => {

src/index.js

+10
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,16 @@ fireEvent.select = (node, init) => {
142142
fireEvent.keyUp(node, init)
143143
}
144144

145+
// if we're running in a test runner that supports afterEach
146+
// then we'll automatically run cleanup afterEach test
147+
// this ensures that tests run in isolation from each other
148+
if (typeof afterEach === 'function' && !process.env.RTL_SKIP_CLEANUP) {
149+
afterEach(async () => {
150+
await asyncAct(async () => {})
151+
cleanup()
152+
})
153+
}
154+
145155
// just re-export everything from dom-testing-library
146156
export * from '@testing-library/dom'
147157
export {render, cleanup, fireEvent, act}

tests/setup-env.js

-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1 @@
11
import '@testing-library/jest-dom/extend-expect'
2-
3-
afterEach(() => {
4-
// have to do a dynamic import so we don't mess up jest mocking for old-act.js
5-
require('../src').cleanup()
6-
})

0 commit comments

Comments
 (0)