react-testing-library icon indicating copy to clipboard operation
react-testing-library copied to clipboard

`findByText` is not working as expected

Open zettadam opened this issue 6 years ago • 2 comments

  • @testing-library/react version: 10.0.3
  • react version: 16.3.1
  • node version: 12.6.1
  • npm (or yarn) version: 6.13.4

What you did:

I wrote a test to check if a button (inside Component) will change its textContent when I click on it.

// test
it('should change button label when clicked', () => {
  const { getByText, findByText, debug } = render(<Component />)
  
  act(() => {
     fireEvent.click(getByText('Delete'))
   })

   debug()

   expect(findByText('Deleting...')).toBeDisabled()
})

The button has attached handler which sets component state flag deleting to true inside the handler (before API call) and then setting it back to false after API call resolved. The button has a prop disabled={deleting} which sets HTML attribute based on the flag.

What happened:

// debug() output
...
<button disabled="" type="button">
  Deleting...
</button>
...
expect(received).toBeDisabled()

    received value must be an HTMLElement or an SVGElement.
    Received has type:  object
    Received has value: {}

      81 |       debug()
      82 | 
    > 83 |       expect(findByText('Deleting...')).toBeDisabled()
         |                                         ^
      84 |     })
      85 |   })

Problem description:

Since debug output renders correctly, I expect the test to pass, but I'm getting an error that received value is not an HTMLElement when it clearly is. There is only one button inside the Component and it is rendered with expected textContent.

By the way, getByText works, but I wanted to use findByText since button label should return to 'Delete' when onClick handler is done and deleting state is set back to false. I wanted to mock it to add timers and I found this behavior very confusing.

zettadam avatar May 02 '20 18:05 zettadam

I solved this issue using waitFor.

act(() => {
  fireEvent.click(getByText('Delete'))
})

expect(getByText('Deleting...')).toBeDisabled()

await waitFor(() => {
  expect(getByText('Delete')).not.toBeDisabled()
}, { timeout: 3000 })

Another option is:

expect(await findByText('Delete')).not.toBeDisabled()

zettadam avatar May 02 '20 19:05 zettadam

You forgot to await:

expect(await findByText('Deleting...')).toBeDisabled()

But in your case, it looks like you don't need to use find and could use get instead

expect(getByText('Deleting...')).toBeDisabled()

kentcdodds avatar May 02 '20 21:05 kentcdodds