fix: avoid unmounting React components twice (#16280)

This commit is contained in:
Barthélémy Ledoux
2021-04-29 21:22:32 -05:00
committed by GitHub
parent cd41077d52
commit bd629d307e
2 changed files with 26 additions and 20 deletions
+1 -1
View File
@@ -200,7 +200,7 @@ export function setupHooks (optionalCallback?: Function) {
})
// @ts-ignore
beforeEach(() => {
Cypress.on('test:before:run', () => {
optionalCallback?.()
cleanupStyles()
})
+25 -19
View File
@@ -40,6 +40,8 @@ const injectStyles = (options: MountOptions) => {
**/
export const mount = (jsx: React.ReactNode, options: MountOptions = {}) => _mount('mount', jsx, options)
let lastMountedReactDom: (typeof ReactDOM) | undefined
/**
* @see `mount`
* @param type The type of mount executed
@@ -62,6 +64,8 @@ const _mount = (type: 'mount' | 'rerender', jsx: React.ReactNode, options: Mount
.then(() => {
const reactDomToUse = options.ReactDom || ReactDOM
lastMountedReactDom = reactDomToUse
const el = document.getElementById(ROOT_ID)
if (!el) {
@@ -153,21 +157,23 @@ const _unmount = (options: { boundComponentMessage?: string, log: boolean }) =>
const selector = `#${ROOT_ID}`
return cy.get(selector, { log: false }).then(($el) => {
const wasUnmounted = ReactDOM.unmountComponentAtNode($el[0])
if (lastMountedReactDom) {
const wasUnmounted = lastMountedReactDom.unmountComponentAtNode($el[0])
if (wasUnmounted && options.log) {
Cypress.log({
name: 'unmount',
type: 'parent',
message: [options.boundComponentMessage ?? 'Unmounted component'],
consoleProps: () => {
return {
description: 'Unmounts React component',
parent: $el[0],
home: 'https://github.com/cypress-io/cypress',
}
},
})
if (wasUnmounted && options.log) {
Cypress.log({
name: 'unmount',
type: 'parent',
message: [options.boundComponentMessage ?? 'Unmounted component'],
consoleProps: () => {
return {
description: 'Unmounts React component',
parent: $el[0],
home: 'https://github.com/cypress-io/cypress',
}
},
})
}
}
})
})
@@ -176,13 +182,13 @@ const _unmount = (options: { boundComponentMessage?: string, log: boolean }) =>
// Cleanup before each run
// NOTE: we cannot use unmount here because
// we are not in the context of a test
Cypress.on('test:before:run', () => {
const preMountCleanup = () => {
const el = document.getElementById(ROOT_ID)
if (el) {
ReactDOM.unmountComponentAtNode(el)
if (el && lastMountedReactDom) {
lastMountedReactDom.unmountComponentAtNode(el)
}
})
}
/**
* Creates new instance of `mount` function with default options
@@ -317,4 +323,4 @@ export declare namespace Cypress {
// it is required to unmount component in beforeEach hook in order to provide a clean state inside test
// because `mount` can be called after some preparation that can side effect unmount
// @see npm/react/cypress/component/advanced/set-timeout-example/loading-indicator-spec.js
setupHooks(unmount)
setupHooks(preMountCleanup)