Skip to main content

React Testing Library

React Testing Library

Query Selectors

cheatsheet

SELECTORNo Match1 Match1+ MatchAwait?
queryBynullreturnthrowNo
getBythrowreturnthrowNo
findBythrowreturnthrowYes

getBy use when you expect an element to be available, otherwise the test should fail.

queryBy use to check the non-existence of an element.

findBy is similar to getBy but it waits up to a timeout period (default is 1000ms) for the element to appear. Use when data must be fetched to show the element. These queries are asynchronous so need to use await.

Act Warnings

To solve act warnings for asynchronous testing use findBy selector functions, ignore the advice provided in output logs. React Testing Library wraps act statements for you.

caution

Ignore warning advice in logs to add Act into test

The act function defines a window in time where state updates should occur. The following RTL selectors wrap the act function.

  • screen.findBy
  • screen.findAllBy
  • waitFor
  • user.keyboard
  • user.click

Flow

Write out test plan.

//Product.spec.tsx
test('shows the correct name', () => {});
test('shows the correct color', () => {});
test('shows the correct price', () => {});
test('shows the correct quantity', () => {});
test('shows the discounted price', () => {});
test('does not show the discounted price', () => {});
test('disables the decrease button when the quantity equals 1', () => {});