Skip to content

Commit

Permalink
Moved cleanup logic into seperate file
Browse files Browse the repository at this point in the history
  • Loading branch information
mpeyper committed Oct 13, 2019
1 parent ba02be0 commit 73c1f61
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 18 deletions.
26 changes: 26 additions & 0 deletions src/cleanup.js
@@ -0,0 +1,26 @@
import { act } from 'react-test-renderer'

let cleanupCallbacks = []

async function cleanup() {
await act(async () => {})
cleanupCallbacks.forEach((cb) => cb())
cleanupCallbacks = []
}

function addCleanup(callback) {
cleanupCallbacks.push(callback)
}

function removeCleanup(callback) {
cleanupCallbacks = cleanupCallbacks.filter((cb) => cb !== callback)
}

// Automatically registers cleanup in supported testing frameworks
if (typeof afterEach === 'function' && !process.env.RHTL_SKIP_AUTO_CLEANUP) {
afterEach(async () => {
await cleanup()
})
}

export { cleanup, addCleanup, removeCleanup }
21 changes: 3 additions & 18 deletions src/index.js
@@ -1,7 +1,6 @@
import React, { Suspense } from 'react'
import { act, create } from 'react-test-renderer'

let cleanupCallbacks = []
import { cleanup, addCleanup, removeCleanup } from './cleanup'

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

function unmountHook() {
act(() => {
cleanupCallbacks = cleanupCallbacks.filter((cb) => cb !== unmountHook)
removeCleanup(unmountHook)
unmount()
})
}

cleanupCallbacks.push(unmountHook)
addCleanup(unmountHook)

let waitingForNextUpdate = null
const resolveOnNextUpdate = (resolve) => {
Expand All @@ -108,18 +107,4 @@ function renderHook(callback, { initialProps, wrapper } = {}) {
}
}

async function cleanup() {
await act(async () => {
await act(async () => {})
cleanupCallbacks.forEach((cb) => cb())
cleanupCallbacks = []
})
}

if (typeof afterEach === 'function' && !process.env.RHTL_SKIP_AUTO_CLEANUP) {
afterEach(async () => {
await cleanup()
})
}

export { renderHook, cleanup, act }

0 comments on commit 73c1f61

Please sign in to comment.