From 95504afd97a1bff0e7793f50fad851ba6791f7fc Mon Sep 17 00:00:00 2001 From: Sunil Pai Date: Tue, 6 Aug 2019 16:10:30 +0100 Subject: [PATCH] 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) --- cleanup-after-each.js | 4 +++- src/__tests__/cleanup-after-each.js | 32 +++++++++++++++++++++++++++++ src/act-compat.js | 2 +- src/cleanup-async.js | 10 +++++++++ 4 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 src/__tests__/cleanup-after-each.js create mode 100644 src/cleanup-async.js diff --git a/cleanup-after-each.js b/cleanup-after-each.js index f0a17c95..9bbba5ce 100644 --- a/cleanup-after-each.js +++ b/cleanup-after-each.js @@ -1 +1,3 @@ -afterEach(require('./dist').cleanup) +afterEach(() => { + return require('./dist/cleanup-async')() +}) diff --git a/src/__tests__/cleanup-after-each.js b/src/__tests__/cleanup-after-each.js new file mode 100644 index 00000000..f59dac9c --- /dev/null +++ b/src/__tests__/cleanup-after-each.js @@ -0,0 +1,32 @@ +import React from 'react' +import {render} from '../index' +import cleanupAsync from '../cleanup-async' + +afterEach(() => { + return cleanupAsync() +}) + +const log = [] +let ctr = 0 + +function App() { + async function somethingAsync() { + await null + log.push(ctr++) + } + React.useEffect(() => { + somethingAsync() + }, []) + return 123 +} + +it('cleanup-after-each does not leave any hanging microtasks: part 1', () => { + render() + expect(document.body.textContent).toBe('123') + expect(log).toEqual([]) +}) + +it('cleanup-after-each does not leave any hanging microtasks: part 2', () => { + expect(log).toEqual([0]) + expect(document.body.innerHTML).toBe('') +}) diff --git a/src/act-compat.js b/src/act-compat.js index 981e6fcd..f812f8a2 100644 --- a/src/act-compat.js +++ b/src/act-compat.js @@ -1,7 +1,7 @@ import React from 'react' import ReactDOM from 'react-dom' -import {reactDomSixteenPointNineIsReleased} from './react-dom-16.9.0-is-released' import * as testUtils from 'react-dom/test-utils' +import {reactDomSixteenPointNineIsReleased} from './react-dom-16.9.0-is-released' const reactAct = testUtils.act const actSupported = reactAct !== undefined diff --git a/src/cleanup-async.js b/src/cleanup-async.js new file mode 100644 index 00000000..0031db56 --- /dev/null +++ b/src/cleanup-async.js @@ -0,0 +1,10 @@ +// This file is for use by the top-level export +// @testing-library/react/cleanup-after-each +// It is not meant to be used directly + +module.exports = async function cleanupAsync() { + const {asyncAct} = require('./act-compat') + const {cleanup} = require('./index') + await asyncAct(async () => {}) + cleanup() +}