react-hooks-testing-library
react-hooks-testing-library copied to clipboard
Exceptions ignore on unmount
To Reproduce
yarn create react-app my-app --template typescript
cd my-app/
yarn add --dev @testing-library/react-hooks react-test-renderer
# add tests (see below)
// issue.test.ts
import {useEffect} from 'react';
import {renderHook} from '@testing-library/react-hooks'
const useMyHook = () => {
useEffect(() => {
return () => {
throw new Error('Ops...') // ,<-- this error never catches by test
}
}, [])
}
it('should fail on unmount', () => {
expect(()=>{
const {unmount, result} = renderHook(() => useMyHook())
result.current
unmount()
}).toThrow()
})
I was going to leave a comment to check result.error
instead of expecting it to throw directly in the test as I assumed this would be hitting the error boundary in the underlying test component we create, but I thought I'd check it before posting and strangely enough, it wasn't being set either.
What's off is that the error boundary is not registering the error at all either, so I'm not sure if we have any ability at all to intercept this error at all.
I'm half wondering if react is not catching this on purpose in the "unmounting" case as the component is going away anyway, but perhaps if the effect cleanup was triggered by changing state it would perhaps end up in the error boundary?
Ok, so I tested a an effect cleanup from changing dependencies with the following test and it does trigger the error boundary and sets result.error
as expected, so this appear to be being ignored by react only on the unmounting case.
const useMyHook = (val: string) => {
useEffect(() => {
return () => {
throw new Error('Ops...') // ,<-- this error never catches by test
}
}, [val])
}
it('should fail on unmount', () => {
const {rerender, result} = renderHook(({ val }) => useMyHook(val), { initialProps: { val: "1" }})
rerender({ val: "2" })
expect(result.error).toBeDefined()
})
FWIW, we do some trickery to hide much of the noisy console output from react errors are thrown in tests which is unfortunately swallowing the output from this error as well. If you change the import to @testing-library/react-hooks/pure
you'll see a big uncaught error log for it as well.