पाठ 13 / 25
Test Behaviour, Not Implementation
The guiding principle of Testing Library.
Users do not see state or props
Testing Library's guiding principle is: the more your tests resemble the way your software is used, the more confidence they can give you. A user sees text, labels, buttons and headings; they do not see component state, hook internals, CSS class names or how many times a child re-rendered. Tests that reach into those details (calling instance methods, asserting on internal state, selecting by class) break when you refactor even though the app still works, and can pass while the user-visible behaviour is broken. Testing Library deliberately exposes DOM-based queries and no access to component instances. The core lives in @testing-library/dom, with wrappers for React, Vue, Svelte, Angular and others sharing the same queries.
Test what the user sees and does
Testing Library pushes you to find elements the way users and assistive technology do, so tests survive refactors.
Implementation-focused versus behaviour-focused
The second test survives a refactor from useState to useReducer.
// brittle: depends on markup details the user never sees
it('toggles', () => {
const { container } = render(<Accordion title="Shipping">Free over $50</Accordion>);
container.querySelector('.accordion__header')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
expect(container.querySelector('.accordion__body--open')).not.toBeNull();
});
// robust: what a user (or screen reader) experiences
it('reveals the content when the heading button is pressed', async () => {
const user = userEvent.setup();
render(<Accordion title="Shipping">Free over $50</Accordion>);
await user.click(screen.getByRole('button', { name: 'Shipping' }));
expect(screen.getByText('Free over $50')).toBeVisible();
expect(screen.getByRole('button', { name: 'Shipping' })).toHaveAttribute('aria-expanded', 'true');
});Test-driving the car, not the engine diagram
A buyer judges a car by driving it: does it start, steer and brake? They do not check which bolt holds the alternator. Component tests should drive the UI the same way.
त्वरित जाँच: Which assertion best follows the Testing Library principle?
- The component state field isSubmitted equals true
- A success message becomes visible after submitting the form
- A div has the class form--submitted
- The submit handler was defined with useCallback
Answer
A success message becomes visible after submitting the form — Assert on what the user can perceive.