I'm testing hooks that modify the global state of a library, so they need to be unmounted before the next test begins. Currently, I'm using this workaround:
import { render as renderImpl, RenderAPI } from 'react-native-testing-library'
const rendered: RenderAPI[] = []
const render: typeof renderImpl = (...args) => {
const elem = renderImpl(...args)
rendered.push(elem)
return elem
}
beforeEach(() => {
rendered.forEach(elem => elem.unmount())
rendered.length = 0
})
Ideally, react-native-testing-library would export a function that lets developers opt-in to this behavior, like the following:
import { setAutoUnmount } from 'react-native-testing-library'
setAutoUnmount(true)
Then I wouldn't need to maintain this code myself. :)
See the workaround.
None.
so they need to be unmounted before the next test begins
Um, why not leveraging Jest APIs then?:
describe('testing hook that messes with globals', () => {
let component;
afterEach(() => component.unmount())
test('1', () => {
component = render(element1)
})
test('2', () => {
component = render(element2)
})
})
Good question! That's certainly a valid solution, but all of my tests are actually ignoring the return value of render, so it's merely bloat to assign to component when I'm not using it.
I see that RTL has something similar built-in and it's called cleanup: https://testing-library.com/docs/react-testing-library/api#cleanup
Could you evaluate if this is the same use case and we could mimic its behavior in RNTL?
That looks perfect! nice find
I'd be happy to get this onboard and turn on by default in v2
v1 #237
v2 #238
Closed via #238
Most helpful comment
v1 #237
v2 #238