Skip to content

Commit 73c1f61

Browse files
committed
Moved cleanup logic into seperate file
1 parent ba02be0 commit 73c1f61

File tree

2 files changed

+29
-18
lines changed

2 files changed

+29
-18
lines changed

src/cleanup.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { act } from 'react-test-renderer'
2+
3+
let cleanupCallbacks = []
4+
5+
async function cleanup() {
6+
await act(async () => {})
7+
cleanupCallbacks.forEach((cb) => cb())
8+
cleanupCallbacks = []
9+
}
10+
11+
function addCleanup(callback) {
12+
cleanupCallbacks.push(callback)
13+
}
14+
15+
function removeCleanup(callback) {
16+
cleanupCallbacks = cleanupCallbacks.filter((cb) => cb !== callback)
17+
}
18+
19+
// Automatically registers cleanup in supported testing frameworks
20+
if (typeof afterEach === 'function' && !process.env.RHTL_SKIP_AUTO_CLEANUP) {
21+
afterEach(async () => {
22+
await cleanup()
23+
})
24+
}
25+
26+
export { cleanup, addCleanup, removeCleanup }

src/index.js

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import React, { Suspense } from 'react'
22
import { act, create } from 'react-test-renderer'
3-
4-
let cleanupCallbacks = []
3+
import { cleanup, addCleanup, removeCleanup } from './cleanup'
54

65
function TestHook({ callback, hookProps, onError, children }) {
76
try {
@@ -77,12 +76,12 @@ function renderHook(callback, { initialProps, wrapper } = {}) {
7776

7877
function unmountHook() {
7978
act(() => {
80-
cleanupCallbacks = cleanupCallbacks.filter((cb) => cb !== unmountHook)
79+
removeCleanup(unmountHook)
8180
unmount()
8281
})
8382
}
8483

85-
cleanupCallbacks.push(unmountHook)
84+
addCleanup(unmountHook)
8685

8786
let waitingForNextUpdate = null
8887
const resolveOnNextUpdate = (resolve) => {
@@ -108,18 +107,4 @@ function renderHook(callback, { initialProps, wrapper } = {}) {
108107
}
109108
}
110109

111-
async function cleanup() {
112-
await act(async () => {
113-
await act(async () => {})
114-
cleanupCallbacks.forEach((cb) => cb())
115-
cleanupCallbacks = []
116-
})
117-
}
118-
119-
if (typeof afterEach === 'function' && !process.env.RHTL_SKIP_AUTO_CLEANUP) {
120-
afterEach(async () => {
121-
await cleanup()
122-
})
123-
}
124-
125110
export { renderHook, cleanup, act }

0 commit comments

Comments
 (0)