Component Testing
A component test should render the component in an environment close enough to production to exercise its behavior. Query elements by accessible role, label, or visible text when possible.
Avoid selecting elements solely by generated class names or implementation-specific DOM structure. Tests that depend on internals break during harmless refactors.
When a component needs data, provide a realistic boundary such as a mocked API layer rather than mocking every internal function.
Behavior-focused test
render(<LoginForm onSubmit={submit} />);
await user.type(screen.getByLabelText(/email/i), "user@example.com");
await user.click(screen.getByRole("button", { name: /sign in/i }));
expect(submit).toHaveBeenCalled();💡 The test describes user behavior instead of inspecting React state.
Key Takeaways
- Query through accessible semantics.
- Test user-visible behavior.
- Avoid asserting implementation details.