The problem
If the only testing a change gets is a developer saying “it works on my machine”, a bug that breaks checkout for 10,000 users can ship.
The pattern
A component test renders one component, together with its child components, into a simulated DOM such as jsdom. It then does what a user would do and checks what the component shows in response. The component’s own markup, state, and event handlers are real. Anything the component gets from outside, such as network requests, the router, or the callbacks its parent passes in, is replaced with a mock that the test controls.
Problem
You clicked through the form once, it worked, you shipped it, but you never tested the error state or what happens when someone pastes an emoji into the email field. Those untested cases are where bugs usually turn up. Without automated tests, every refactor is scary. If you change a shared button component, you might have broken twelve pages, or you might not have. You won’t know until QA spends a week clicking through everything or customers start complaining.
Other kinds of test only cover part of the problem. A unit test of a validation function can pass even if the form never calls that function, and an end-to-end test that runs the whole app in a real browser is too slow to run for each state of each component.
Solution
A unit test, by comparison, calls a function directly and renders nothing. Integration Testing checks that several components, the router, and the store work together, and E2E Testing runs the whole app in a real browser against a real backend. Component tests can cover the happy path, the error path, the loading state, the empty state, and the edge cases you’d never remember to check manually.
The idea behind Testing Library is that you test components the way people use them. Your tests find elements by their accessible names, click and type the way a user would, and then check what appears on screen. Implementation details like internal state stay out of the tests. Testing Library has two ways to simulate input. fireEvent.click dispatches one click event, while userEvent from @testing-library/user-event sends the whole sequence of pointer, focus, and keyboard events that a real click or keystroke produces, so the examples here use userEvent.
If you mock the APIs a component calls, the tests stay fast and give the same result each time. A test with mocked responses runs in milliseconds, and it can’t fail because the server was slow or down.
Example
All of these tests are for one component, a login form. It calls the onSubmit function it’s given, shows “Logging in…” on the button until that call finishes, and shows an error if the call fails. This is the React version, and the other frameworks’ versions behave the same way.
function LoginForm({ onSubmit }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [status, setStatus] = useState('idle'); // 'idle', 'sending' or 'failed'
async function handleSubmit(event) {
event.preventDefault();
setStatus('sending');
try {
await onSubmit({ email, password });
setStatus('idle');
} catch {
setStatus('failed');
}
}
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input type="email" value={email} onChange={e => setEmail(e.target.value)} />
</label>
<label>
Password
<input type="password" value={password} onChange={e => setPassword(e.target.value)} />
</label>
{status === 'failed' && <p role="alert">Wrong email or password</p>}
<button disabled={status === 'sending'}>
{status === 'sending' ? 'Logging in...' : 'Log in'}
</button>
</form>
);
}
Testing the Happy Path
The test types into the two fields, clicks the button, and checks that onSubmit got the values. The test in each tab finds the fields by their labels and the button by its role and name, so the test doesn’t depend on the form’s markup or class names.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
test('submits the email and password', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn().mockResolvedValue();
render(<LoginForm onSubmit={handleSubmit} />);
await user.type(screen.getByLabelText('Email'), 'user@example.com');
await user.type(screen.getByLabelText('Password'), 'password123');
await user.click(screen.getByRole('button', { name: 'Log in' }));
expect(handleSubmit).toHaveBeenCalledWith({
email: 'user@example.com',
password: 'password123'
});
}); import { render, screen } from '@testing-library/vue';
import userEvent from '@testing-library/user-event';
import LoginForm from './LoginForm.vue';
test('submits the email and password', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn().mockResolvedValue();
render(LoginForm, { props: { onSubmit: handleSubmit } });
await user.type(screen.getByLabelText('Email'), 'user@example.com');
await user.type(screen.getByLabelText('Password'), 'password123');
await user.click(screen.getByRole('button', { name: 'Log in' }));
expect(handleSubmit).toHaveBeenCalledWith({
email: 'user@example.com',
password: 'password123'
});
}); import { render, screen } from '@testing-library/svelte';
import userEvent from '@testing-library/user-event';
import LoginForm from './LoginForm.svelte';
test('submits the email and password', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn().mockResolvedValue();
render(LoginForm, { props: { onSubmit: handleSubmit } });
await user.type(screen.getByLabelText('Email'), 'user@example.com');
await user.type(screen.getByLabelText('Password'), 'password123');
await user.click(screen.getByRole('button', { name: 'Log in' }));
expect(handleSubmit).toHaveBeenCalledWith({
email: 'user@example.com',
password: 'password123'
});
}); import { within } from '@testing-library/dom';
import userEvent from '@testing-library/user-event';
import './login-form.js';
test('submits the email and password', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn().mockResolvedValue();
const form = document.createElement('login-form');
form.onSubmit = handleSubmit; // a function, so it's set as a property
document.body.appendChild(form);
// Testing Library's queries stop at a shadow root,
// so the test starts its queries from inside it
const view = within(form.shadowRoot);
await user.type(view.getByLabelText('Email'), 'user@example.com');
await user.type(view.getByLabelText('Password'), 'password123');
await user.click(view.getByRole('button', { name: 'Log in' }));
expect(handleSubmit).toHaveBeenCalledWith({
email: 'user@example.com',
password: 'password123'
});
form.remove();
}); Testing the Loading and Error States
The form’s state depends on what the mock for onSubmit returns. A promise that never settles keeps the form in its loading state, and a rejected promise puts it in its error state. The tests for the other frameworks only differ in their render call, as in the tabs above.
test('disables the button while the login is in progress', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn(() => new Promise(() => {})); // never settles
render(<LoginForm onSubmit={handleSubmit} />);
await user.click(screen.getByRole('button', { name: 'Log in' }));
expect(screen.getByRole('button', { name: 'Logging in...' })).toBeDisabled();
});
test('shows an error when the login fails', async () => {
const user = userEvent.setup();
const handleSubmit = jest.fn().mockRejectedValue(new Error('Unauthorized'));
render(<LoginForm onSubmit={handleSubmit} />);
await user.click(screen.getByRole('button', { name: 'Log in' }));
// findByRole retries until the alert appears
expect(await screen.findByRole('alert')).toHaveTextContent('Wrong email or password');
});
Behavior Instead of Implementation
This test checks the same error state, but it finds the elements by their tag names and where they are in the markup.
// ❌ Depends on the markup instead of what the user sees
test('shows an error when the login fails', async () => {
const handleSubmit = jest.fn().mockRejectedValue(new Error('Unauthorized'));
const { container } = render(<LoginForm onSubmit={handleSubmit} />);
await userEvent.click(container.querySelector('form > button'));
await waitFor(() => {
expect(container.querySelector('form > p')).not.toBeNull();
});
});
If you later wrap the button in a <div> for layout, or change the error from a <p> to a <div>, this test fails even though the form works exactly as before. The earlier test, which finds the button by its name and the error by its alert role, still passes after both changes, and it only fails when the user would notice a difference, such as the error message not appearing. A test that asserts on a CSS class or on the value of status has the same problem.
The same approach works for the other things you might want to check about a component. If the component uses context, the test can wrap it in a provider with a mock value, which Context Testing covers. Accessibility Testing adds automated checks such as axe to the rendered output, Snapshot Testing compares the whole output with a saved copy, and Stateful Logic Testing tests hooks and stores without rendering a component.
Benefits
- A component test catches bugs that a unit test of a function misses, such as a handler that was never attached to the button, a label that isn’t connected to its input, or an error message that never renders.
- It runs in milliseconds in a simulated DOM, without a browser or a backend, so you can test far more states of a component than you could with end-to-end tests.
- Loading and error states are easy to produce, because the test controls what the mocked call returns. In an end-to-end test, you’d have to make a real backend slow or make it fail.
- When a component test fails, you only have one component to check, while a failed end-to-end test could be caused by anything in the app.
- Tests that find elements by role and label keep passing when you restructure the markup, and a field the test can’t find by its label is often a real accessibility problem.
- A component that’s hard to test often has design problems, so writing tests can push you toward a better design.
Tradeoffs
- Tests take time to write, and thorough tests can add a lot to the initial development time, even though they save debugging time later.
- Tests only check the cases you thought of, so the code can still break in production on an edge case you missed, even though the whole suite passes.
- Mocking adds complexity and can hide integration problems, since a test might pass with a mocked API that behaves differently from the real one, so you still need some integration and end-to-end tests.
- A simulated DOM such as jsdom doesn’t lay out the page, so a component test can’t detect that a button is hidden behind another element.
- If you have to wait three minutes for a slow test suite after every change, you’ll probably stop running the tests.
- Async code is hard to test, because
waitForandacthave subtle timing behavior that can lead to flaky tests if you don’t understand them well. - Deciding what to test takes judgment. Testing too much detail makes the suite brittle, and testing too little misses important cases.
- Outdated tests can be worse than no tests, because you still have to maintain them but they no longer catch real bugs. A high coverage figure can give you false confidence in the same way.
Summary
Component tests render one component with its outside dependencies mocked, and check that it responds correctly to user interactions. If you write the tests from the user’s point of view and keep implementation details out of them, they catch real bugs and you can still refactor freely.