React-native-testing-library: Automatic unmount of rendered components at end of each test

Created on 18 Nov 2019  路  7Comments  路  Source: callstack/react-native-testing-library

Describe the Feature

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. :)

Possible Implementations

See the workaround.

Related Issues

None.

feature request

Most helpful comment

v1 #237
v2 #238

All 7 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thymikee picture thymikee  路  9Comments

kblankenship1989 picture kblankenship1989  路  3Comments

mym0404 picture mym0404  路  11Comments

ghost picture ghost  路  7Comments

acollazomayer picture acollazomayer  路  3Comments