testing-library/testing-library-docs

Prefer `findByRole` query over using `waitFor` + `getByRole`

shawnesquivel opened this issue · 4 comments

Describe the bug A clear and concise description of what the bug is.

To Reproduce Steps to reproduce the behavior:

  1. Following the example https://github.com/testing-library/testing-library-docs/blob/main/docs/react-testing-library/example-intro.mdx
  2. On Line 96
  await waitFor(() => screen.getByRole('heading'))
  1. Throws the eslint error
Prefer `findByRole` query over using `waitFor` + `getByRole`

Expected behavior Expect to wait until "heading" element is rendered by the Fetch.js component (see step 1 example for file)

  • OS: Windows 10

Additional context
When using the CLI fix recommendation, it changes the line to read

  await screen.findByRole("heading");

However, the same error is thrown.

Additional Resources
https://github.com/testing-library/eslint-plugin-testing-library/blob/main/docs/rules/prefer-find-by.md
https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#using-waitfor-to-wait-for-elements-that-can-be-queried-with-find

Good catch. Would you be willing to open a PR using the preferred solution instead?

Good catch. Would you be willing to open a PR using the preferred solution instead?

Hi Sebastian, using the preferred solution didn't seem to fix the error for me. I replaced Line 96 with this:

  await screen.findByRole('heading')

But got the same error message. Any recommendations?

@shawnesquivel screen.findByRole is the preferred way to do this.
I would say that you can go ahead with the changes, fixing the example can be done in a follow-up PR, or within the same PR if you want to do that.

Great, I went ahead with the PR implementing screen.findByRole but was unable to fix the overall example, so I'll let someone else do that in a separate PR.

#1189