In React Testing Library, it provides screen
query methods like
screen.getByRole('button', {name: /submit/i})
There are 3 commands available get
, query
& find
. The usage depends upon the use test case.
| | No Match | 1 Match | 1+ Match | Await? |
| ------- | -------- | ------- | -------- | ------ |
| queryBy | null | return | throw | No |
| getBy | throw | return | throw | No |
| findBy | throw | return | throw | Yes |
getBy : expect element to be in DOM
queryBy : expect element not to be in DOM
findBy : expect element to appear async
For examples:
expect(screen.getByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
const submitButton = await screen.findByRole('button', {name: /submit/i})
References:
- From my favourite teacher's blog post Kent C. Dodds: Common mistakes with react testing library
- https://testing-library.com/docs/queries/about/