1
describe('<CustomTooltip />', () => {
  it('should show tooltip text', async () => {
    const { container, unmount } = render(<CustomTooltip text='Tooltip Text' />)

    userEvent.hover(container.querySelector('svg'))
    await screen.findByText('Tooltip Text')

    screen.debug()
    unmount()  // ?? is it necessary to call unmount after each test cases?
  })

  it('check if there is an mounted component', () => {
    screen.debug()
  })
})

Is it necessary to call unmount after each test cases? Because I've added useEffect in the CustomTooltip component, and Unmounted is logged before the second test case. And even the second test case screen.debug output is <body />.

  useEffect(() => {
    console.log('Mounted')
    return () => console.log('Unmounted')
  }, [])

I asked this because i saw a custom implementation for render in test utils to unmount component after each test cases, and I'm curious to know if this is really important.

let lastMount = null;
const _render = (...args) => {
  lastMount = render(...args);
  return lastMount;
};


afterEach(() => {
  if (lastMount)
    lastMount.unmount();

  lastMount = null;
});
Henok Tesfaye
  • 8,287
  • 13
  • 47
  • 84
  • The Test Function will exit on its own, when the test case finishes and cleanup (unmount) the component. To call unmount() fn from the renderer object is normaly not necessary. It would be just in special cases necessary, when e.q. there is running something async on component's background, maybe a network call and the Test Function would end without to receive the async response from the component. This situation is a race condition. Then probably you need to unmount the component before it'll break the test case. – lortschi Jan 17 '23 at 13:56

1 Answers1

0

It depends on the testing framework that you are using. If you are using jest, for instance, it's not needed.

Here is a reference to this suggestion https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#using-cleanup

For a long time now cleanup happens automatically (supported for most major testing frameworks) and you no longer need to worry about it