Sub topic 1
Why Test Behavior Instead of Implementation
Prerequisites
Assume you know React function components, props, state, hooks, basic HTML semantics, and JavaScript async/await. You should also know a test runner such as Jest or Vitest.
Test What the User Can Observe
React Testing Library encourages tests based on user-facing behavior. A user sees text, buttons, labels, and state changes. A user does not see a component's state variables, hook calls, or internal helper functions.
Behavior-focused tests are less fragile. You can change state management or split one component into several components without rewriting a test if the user experience stays the same.
Set Up the Test Environment
A test environment needs a runner, a browser-like DOM, and readable DOM assertions. jsdom provides the DOM inside Node.js. jest-dom adds matchers such as toBeInTheDocument.
For Jest, configure the environment and load the matchers once:
// jest.config.js
export default {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};
// jest.setup.js
import '@testing-library/jest-dom';For Vitest, use environment: 'jsdom' and import @testing-library/jest-dom/vitest in the setup file.
Render Components and Use `screen`
render mounts a component in the test DOM. screen queries that DOM. Prefer queries that describe what a user can access, such as a button's role and accessible name.
import { render, screen } from '@testing-library/react';
import { Counter } from './Counter';
test('shows the initial count', () => {
render(<Counter />);
expect(screen.getByText('Count: 0')).toBeInTheDocument();
});The flow is:
Choose the Correct Query Variant
| Query | Use it when | Result |
|---|---|---|
| `getBy` | The element should exist now | Returns it or throws |
| `queryBy` | The element may be absent | Returns it or `null` |
| `findBy` | The element appears asynchronously | Returns a promise |
Use getBy for normal synchronous assertions. Use queryBy to verify that something is absent. Use findBy when rendering or an interaction causes an asynchronous update. Avoid using findBy merely because it is available; it makes a synchronous test unnecessarily asynchronous.
Exercise
Which query should verify that a loading message disappears after an asynchronous request?
Show answer
Use queryByText after waiting for the result, or use findBy... to wait for the replacement content and then queryByText for the loading message.