Description
Describe the feature you'd like:
I've had this problem on a personal project to try and create custom hooks.
The useEffect
hook accepts a function as argument, and if this function returns another function, React will call it when the component unmounts
useEffect(() => {
subscribe(channel)
return () => {
// componentWillUnmount
unsubscribe(channel)
}
})
The testHook API already can test the useEffect call, but I couldn't find a way to test the callback on unmount.
Suggested implementation:
The testHook
function renders a wrapper component and already has access to the unmount
function. My suggestion is to simply return it inside an object.
function testHook(callback) {
const { unmount } = render(<TestHook callback={callback} />)
return { unmount }
}
This is simple to do, and I think it is clear too. Also it can be expand to other important return values when needed.
Describe alternatives you've considered:
My first thought was to return the unmount function alone
function testHook(callback) {
const { unmount } = render(<TestHook callback={callback} />)
return unmount
}
I did this to mimic the behavior of the useEffect
. However, it didn't look good to me, as it would get all the usage of testHook
return.
Teachability, Documentation, Adoption, Migration Strategy:
I've took the liberty to create a fork containing my sugestion.
https://github.com/Andrewmat/react-testing-library
I've already tested in my personal project using yarn link
and it worked.
If this feature is considered, I'd be glad to make a pull request of it.