File size: 3,023 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
import * as React from 'react'
import {render, cleanup} from '../'
test('cleans up the document', () => {
const spy = jest.fn()
const divId = 'my-div'
class Test extends React.Component {
componentWillUnmount() {
expect(document.getElementById(divId)).toBeInTheDocument()
spy()
}
render() {
return <div id={divId} />
}
}
render(<Test />)
cleanup()
expect(document.body).toBeEmptyDOMElement()
expect(spy).toHaveBeenCalledTimes(1)
})
test('cleanup does not error when an element is not a child', () => {
render(<div />, {container: document.createElement('div')})
cleanup()
})
test('cleanup runs effect cleanup functions', () => {
const spy = jest.fn()
const Test = () => {
React.useEffect(() => spy)
return null
}
render(<Test />)
cleanup()
expect(spy).toHaveBeenCalledTimes(1)
})
describe('fake timers and missing act warnings', () => {
beforeEach(() => {
jest.resetAllMocks()
jest.spyOn(console, 'error').mockImplementation(() => {
// assert messages explicitly
})
jest.useFakeTimers()
})
afterEach(() => {
jest.restoreAllMocks()
jest.useRealTimers()
})
test('cleanup does not flush microtasks', () => {
const microTaskSpy = jest.fn()
function Test() {
const counter = 1
const [, setDeferredCounter] = React.useState(null)
React.useEffect(() => {
let cancelled = false
Promise.resolve().then(() => {
microTaskSpy()
// eslint-disable-next-line jest/no-if, jest/no-conditional-in-test -- false positive
if (!cancelled) {
setDeferredCounter(counter)
}
})
return () => {
cancelled = true
}
}, [counter])
return null
}
render(<Test />)
cleanup()
expect(microTaskSpy).toHaveBeenCalledTimes(0)
// console.error is mocked
// eslint-disable-next-line no-console
expect(console.error).toHaveBeenCalledTimes(0)
})
test('cleanup does not swallow missing act warnings', () => {
const deferredStateUpdateSpy = jest.fn()
function Test() {
const counter = 1
const [, setDeferredCounter] = React.useState(null)
React.useEffect(() => {
let cancelled = false
setTimeout(() => {
deferredStateUpdateSpy()
// eslint-disable-next-line jest/no-conditional-in-test -- false-positive
if (!cancelled) {
setDeferredCounter(counter)
}
}, 0)
return () => {
cancelled = true
}
}, [counter])
return null
}
render(<Test />)
jest.runAllTimers()
cleanup()
expect(deferredStateUpdateSpy).toHaveBeenCalledTimes(1)
// console.error is mocked
// eslint-disable-next-line no-console
expect(console.error).toHaveBeenCalledTimes(1)
// eslint-disable-next-line no-console
expect(console.error.mock.calls[0][0]).toMatch(
'a test was not wrapped in act(...)',
)
})
})
|