[React Testing] Assert That Something is NOT Rendered with React Testing Library (with rerender & query)

You can use 'rerender' for a component when its props changed.

Then if you wnat to check the alert message has gone when we rerender, you need to use 'queryByRole' instead of 'getByRole', because 'getByRole' will throw when the element is not there

test('rerender the component when the prop changes', () => {
  const { getByLabelText, getByRole, queryByRole, rerender } = render(
    <FavoriteNumber />,
  )
  const input = getByLabelText(/favorite number/i)
  user.type(input, '10')
  expect(getByRole('alert')).toHaveTextContent(/the number is invalid/i)

  // rerender with a different prop
  rerender(<FavoriteNumber max={10} />)
  expect(queryByRole('alert')).not.toBeInTheDocument()
})

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12810735.html
今日推荐