React Testing Library
React Testing Library
Query Selectors
SELECTOR | No Match | 1 Match | 1+ Match | Await? |
---|---|---|---|---|
queryBy | null | return | throw | No |
getBy | throw | return | throw | No |
findBy | throw | return | throw | Yes |
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', () => {});