Search code examples
react-testing-library

How to look for elements after rerender in React Testing Library?


I have this piece of code where I destructure first container and rerender form rendering of Table. Then after a several steps I rerender the table. Then I check, using container if the value in component with testid 'selected-value' is not what it was chosen before rerendering. But, the value persisted despite rerendering. Which means either that the Table was not rerendered or that the container is still referring to the container before rerender. I do not know how to look for the component with testid 'selected-value' after rerendering.

  const { container, rerender } = render(<Table {...props} />)

  const select = container.querySelector("[data-testid='select']")

  fireEvent.click(select)

  const selectOption = container.querySelector("[data-testid='select-option']")
  const optionValue = selectOption.textContent

  fireEvent.click(selectOption)

  rerender(<Table {...props} />)

  expect(container.querySelector("[data-testid='selected-value']").textContent).toBe(lastValue)

Solution

  • I am testing the scenario where Table needs to unmount and rerender completely from scratch but keeping in its state (or not keeping - depends on the setup) the value chosen in associated dropdown (for example on page refresh). To mimick this scenario I use the following code:

          const props = {
            rows,
            config
          }
          const { unmount } = render(<Table {...props} />)
          const select = screen.getByTestId('select')
    
          fireEvent.click(select)
    
          const selectOption = screen.getByTestId('select-option')
          const optionValue =  selectOption.textContent
    
          fireEvent.click(selectOption)
    
          unmount()
          render(<Table {...props} />)
    
          const selectedValue = screen.getByTestId('selected-value').textContent
    
          expect(selectedValue).toBe(optionValue)