Advertise here — become a partner
Advertise here — become a partner
Programming / Tech

Testing in React: Testing Library and beyond

You are an engineer specialized in frontend testing. Help me test React: the project is [DESCRIBE: what it does, stack — Jest/Vitest, RTL?, TypeScript?], the target is [WHAT TO TEST: specific component — I can paste, custom hooks, flows with API, complex form, start the suite from scratch], and the situation is [ZERO TESTS/BRITTLE TESTS THAT TEST IMPLEMENTATION/SNAPSHOT FOR EVERYTHING WITHOUT KNOWING WHY/STRATEGY DISCUSSION]. Deliver: the Testing Library philosophy that changes everything (test like the USER uses — what they see and do, not what's inside the component: the test that survives refactoring; the query hierarchy as accessibility compass — getByRole ALWAYS first — and the bonus: test hard to write with role exposes inaccessible component —, then LabelText/Text, testid as last resort confessed; userEvent instead of fireEvent — the real click with its entire event chain), the tests written for my target (the component with interaction — render, userEvent, the assert on visible result: the complete example of MY case; the async done right — findBy/waitFor waiting for what the user would wait for, never empty-faith waitFor; custom hook with renderHook — when to test it directly and when through the component; complete form — fill, submit, validation error appearing, success), the API mocked in the right place (MSW intercepting at the network layer — the component doesn't even know it's a test: the handlers for my case set up, the error scenario and the slowness tested; module mocking only for what isn't HTTP — the clock, the router: how and when), the snapshot in its rightful place (almost never — the giant snapshot everyone approves without reading doesn't test anything: the rare legitimate uses and the explicit assert in place), the frontend pyramid strategy (many component/light integration tests — the RTL sweet spot; the few and precise e2e with Playwright/Cypress on the flow that pays the bills — which is mine; visual testing when the product is the pixel), the patterns of healthy suite (shared setup with renderWithProviders — the wrapper of theme/router/query built, data factories, the independent test that runs solo and in any order, fast — and flaky handled as bug), and if you paste component: the complete suite written with the reasoning of each test commented — including what I decided NOT to test and why. Goal: tests that break when the user would suffer — and only then.
Advertise here — become a partner Advertise here — become a partner