Frontend development · Intermediate · 25 min
Test UI code with Vitest and DOM Testing Library
By Padding · Updated 18 Nov 2026
Node.js 26.13 · Vitest 5.1.1 · happy-dom 21.0.4 · checked on node:26
You will have a fast Vitest suite for a plain-JavaScript sign-up form that types and clicks like a user, mocks fetch, reports coverage and fails when an error message stops being announced.
On this page
Most form bugs are not in the validation rules. They are in what happens around them: the error text appears but no screen reader hears it, focus stays on the button so the user has no idea what went wrong, or a failed network request leaves the form silent. These are easy to break while tidying markup, and a quick look in the browser rarely catches them.
In this tutorial you write a small sign-up form in plain JavaScript, with no framework, and test it the way a person uses it. Vitest runs the tests. happy-dom gives each test a simulated browser document in Node.js, so the suite starts in about a second and needs no real browser. DOM Testing Library finds elements by role and label, the same way people and assistive technology find them, and user-event types and clicks with realistic event sequences. You mock fetch so no real server is needed, run watch mode while you work, and measure coverage.
The suite you finish with has one job worth calling out: if someone removes the link between an input and its error message, so the error stops being announced, the tests fail. You will prove it by breaking the code on purpose.
What this does not cover: layout, colours and real browser behaviour. happy-dom has no rendering engine. For those, use real browser tests, which the Playwright tutorial linked at the end covers.
Step 1 · Set up the project
Make a throwaway folder, start a package and install the test tools as development dependencies. Every version is pinned so your results match this tutorial:
mkdir -p ~/signup-tests-demo
cd ~/signup-tests-demo
npm init -y > /dev/null
npm pkg set type=module
npm install --save-dev vitest@5.1.1 happy-dom@21.0.4 @testing-library/dom@10.4.2 @testing-library/user-event@14.6.13npm pkg set type=module makes .js files ES modules, so import and export work without a build step.
Vitest reads Vite's config file. Tell it to give every test file a happy-dom document instead of the plain Node.js globals, and add two scripts:
cd ~/signup-tests-demo
cat > vite.config.js <<'JS'
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'happy-dom',
},
});
JS
npm pkg set scripts.test=vitest
npm pkg set "scripts.test:run=vitest run"
npx vitest --versionjsdom is the other common choice for environment. It follows browser behaviour more closely in some corners and is slower to start. happy-dom is enough for forms, events and accessibility queries, and every query in this tutorial works the same in both.
Check it worked
npx vitest --version prints a line starting vitest/5.1.1. package.json now has "type": "module", the two scripts and four packages under devDependencies.
Step 2 · Write the sign-up form module
The module exports one function, mountSignupForm, that draws the form into any element and wires up its behaviour. Keeping it a function that takes a container is what makes it testable: a test can mount a fresh copy into an empty document every time.
cd ~/signup-tests-demo
mkdir -p src
cat > src/signup.js <<'JS'
// Messages in one place, so they are easy to review and translate.
export const messages = {
emailMissing: 'Enter your email address',
emailFormat: 'Enter an email address in the format name@example.com',
passwordShort: 'Password must be at least 8 characters',
emailTaken: 'An account with this email already exists',
created: 'Account created. Check your inbox to confirm your email.',
serverError: 'Something went wrong on our side. Try again in a few minutes.',
offline: 'Could not reach the server. Check your connection and try again.',
};
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function checkEmail(value) {
if (value === '') return messages.emailMissing;
if (!EMAIL_PATTERN.test(value)) return messages.emailFormat;
return '';
}
function checkPassword(value) {
return value.length < 8 ? messages.passwordShort : '';
}
function linkDescription(input, id) {
const ids = (input.getAttribute('aria-describedby') || '').split(' ').filter(Boolean);
if (!ids.includes(id)) input.setAttribute('aria-describedby', [id, ...ids].join(' '));
}
function unlinkDescription(input, id) {
const ids = (input.getAttribute('aria-describedby') || '').split(' ').filter((x) => x && x !== id);
if (ids.length) input.setAttribute('aria-describedby', ids.join(' '));
else input.removeAttribute('aria-describedby');
}
function showError(input, message) {
const error = input.form.querySelector(`#${input.id}-error`);
error.textContent = message;
error.hidden = false;
input.setAttribute('aria-invalid', 'true');
linkDescription(input, error.id);
}
function clearError(input) {
const error = input.form.querySelector(`#${input.id}-error`);
error.textContent = '';
error.hidden = true;
input.removeAttribute('aria-invalid');
unlinkDescription(input, error.id);
}
export function mountSignupForm(container, { endpoint = '/api/signup' } = {}) {
container.innerHTML = `
<form class="signup" novalidate>
<h2>Create your account</h2>
<div class="field">
<label for="signup-email">Email</label>
<input id="signup-email" name="email" type="email" autocomplete="email">
<p id="signup-email-error" class="error" hidden></p>
</div>
<div class="field">
<label for="signup-password">Password</label>
<p id="signup-password-hint" class="hint">At least 8 characters</p>
<input id="signup-password" name="password" type="password"
autocomplete="new-password" aria-describedby="signup-password-hint">
<p id="signup-password-error" class="error" hidden></p>
</div>
<button type="submit">Create account</button>
<p class="status" role="status"></p>
</form>`;
const form = container.querySelector('form');
const email = form.elements.email;
const password = form.elements.password;
const button = form.querySelector('button');
const status = form.querySelector('[role="status"]');
form.addEventListener('submit', async (event) => {
event.preventDefault();
status.textContent = '';
const problems = [
[email, checkEmail(email.value.trim())],
[password, checkPassword(password.value)],
];
for (const [input, message] of problems) {
if (message) showError(input, message);
else clearError(input);
}
const firstInvalid = problems.find(([, message]) => message);
if (firstInvalid) {
firstInvalid[0].focus();
return;
}
button.disabled = true;
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: email.value.trim(), password: password.value }),
});
if (response.status === 409) {
showError(email, messages.emailTaken);
email.focus();
} else if (!response.ok) {
status.textContent = messages.serverError;
} else {
status.textContent = messages.created;
form.reset();
}
} catch {
status.textContent = messages.offline;
} finally {
button.disabled = false;
}
});
return form;
}
JSThe parts the tests will lean on:
novalidateon the form. The browser's own validation bubbles are switched off so the module can show its own messages in the page. The constraint validation tutorial linked at the end shows the other approach, keeping the browser's checks and styling them.- Errors joined by
aria-describedby.showErrorputs the message in a paragraph next to the input and adds that paragraph's id to the input'saria-describedby. That attribute is what makes a screen reader read the error when the field gets focus. The error is linked only while it is showing, because a description pointing at a hidden element is still read out. - Focus moves to the first problem. A user who presses Create account and hears nothing has no way to know what failed. Moving focus to the first invalid field reads its label and its error together.
- A
role="status"paragraph for messages that belong to the whole form. Screen readers announce changes to it politely, after whatever they are reading. - A plain message when the network fails. A dropped mobile connection or a data bundle that runs out mid-sign-up is common on prepaid plans, in many African markets and elsewhere. The form tells the person what happened and what to do, rather than spinning or failing silently.
Check it worked
ls src lists signup.js. Run node --check src/signup.js: it prints nothing, which means the file parses. Nothing has tested its behaviour yet; that starts in the next step.
Step 3 · Render the form and query it like a user
Each test needs a fresh form. Write a small helper that mounts one into the happy-dom document and sets up user-event, and clear the document after every test so nothing leaks from one test into the next:
cd ~/signup-tests-demo
mkdir -p test
cat > test/render-form.js <<'JS'
import { afterEach } from 'vitest';
import userEvent from '@testing-library/user-event';
import { mountSignupForm } from '../src/signup.js';
afterEach(() => {
document.body.innerHTML = '';
});
export function renderSignupForm(options) {
const container = document.createElement('div');
document.body.append(container);
mountSignupForm(container, options);
return { user: userEvent.setup() };
}
JSNow the first test file. It does not look anything up by class name or id. It uses screen, which searches the whole document.body, and asks for elements by role and accessible name:
cd ~/signup-tests-demo
cat > test/render.test.js <<'JS'
import { describe, expect, it } from 'vitest';
import { screen } from '@testing-library/dom';
import { renderSignupForm } from './render-form.js';
describe('sign-up form', () => {
it('has the heading, fields and button a person looks for', () => {
renderSignupForm();
expect(screen.getByRole('heading', { name: 'Create your account' })).toBeTruthy();
expect(screen.getByRole('textbox', { name: 'Email' })).toBeTruthy();
expect(screen.getByLabelText('Password')).toBeTruthy();
expect(screen.getByRole('button', { name: 'Create account' })).toBeTruthy();
});
it('shows the password hint as the field description', () => {
renderSignupForm();
const password = screen.getByLabelText('Password');
const hint = screen.getByText('At least 8 characters');
expect(password.getAttribute('aria-describedby')).toBe(hint.id);
});
it('starts with no errors and an empty status', () => {
renderSignupForm();
expect(screen.queryByText(/must be at least/)).toBeNull();
expect(screen.getByRole('status').textContent).toBe('');
});
});
JS
npx vitest runHow to choose a query, from best to last resort:
getByRolewithname. This is how screen reader users move around a page, and it fails if a button loses its text or a field loses its label.getByLabelText. For fields that have no ARIA role. A password input is one: HTML gives it none, sogetByRole('textbox')does not find it.getByText. For plain text such as hints and messages.getByTestId. Only when nothing a user can perceive identifies the element.
Each getBy query throws when it finds no match, or more than one, so the toBeTruthy() is there only to make the intent readable. queryBy returns null instead of throwing, which is what you want when checking that something is absent. findBy, which you meet later, waits for an element to appear.
Check it worked
The output lists test/render.test.js with 3 tests and ends with a summary showing 3 passed. Try a failure: change 'Create account' in the first test to 'Sign up' and run npx vitest run again. The error says it is unable to find an accessible element with the role "button" and name "Sign up", and prints the roles it did find. Change it back.
Step 4 · Type and click with user-event
user-event drives the form the way a person would. user.click sends pointer and mouse events and moves focus. user.type clicks into a field and presses one key per character, so every keydown, input and keyup handler runs. Each call returns a promise, so always await it.
These tests check what the person perceives after a failed submit: which field is described by which error, whether it is marked invalid, and where focus is.
cd ~/signup-tests-demo
cat > test/validation.test.js <<'JS'
import { describe, expect, it } from 'vitest';
import { screen } from '@testing-library/dom';
import { renderSignupForm } from './render-form.js';
import { messages } from '../src/signup.js';
describe('validation', () => {
it('announces a missing email and moves focus to it', async () => {
const { user } = renderSignupForm();
await user.click(screen.getByRole('button', { name: 'Create account' }));
const email = screen.getByRole('textbox', {
name: 'Email',
description: messages.emailMissing,
});
expect(email.getAttribute('aria-invalid')).toBe('true');
expect(document.activeElement).toBe(email);
});
it('explains the email format', async () => {
const { user } = renderSignupForm();
await user.type(screen.getByRole('textbox', { name: 'Email' }), 'ada.example.com');
await user.click(screen.getByRole('button', { name: 'Create account' }));
expect(
screen.getByRole('textbox', { name: 'Email', description: messages.emailFormat }),
).toBeTruthy();
});
it('links a short password to its error and keeps the hint', async () => {
const { user } = renderSignupForm();
await user.type(screen.getByRole('textbox', { name: 'Email' }), 'ada@example.com');
await user.type(screen.getByLabelText('Password'), 'short');
await user.keyboard('{Enter}');
const password = screen.getByLabelText('Password');
const error = screen.getByText(messages.passwordShort);
const hint = screen.getByText('At least 8 characters');
expect(password.getAttribute('aria-describedby').split(' ')).toEqual([error.id, hint.id]);
expect(document.activeElement).toBe(password);
});
it('clears an error once the field is fixed', async () => {
const { user } = renderSignupForm();
const button = screen.getByRole('button', { name: 'Create account' });
await user.click(button);
expect(screen.getByText(messages.emailMissing)).toBeTruthy();
await user.type(screen.getByRole('textbox', { name: 'Email' }), 'ada@example.com');
await user.click(button);
expect(screen.queryByText(messages.emailMissing)).toBeNull();
expect(screen.getByRole('textbox', { name: 'Email' }).hasAttribute('aria-invalid')).toBe(false);
});
});
JS
npx vitest runThe description option on getByRole matches the element's accessible description, the text a screen reader reads after the name. Here it is built from aria-describedby. So the first test only passes if the error text exists and is connected to the Email field, not merely somewhere on the page. Password inputs have no role, so the third test checks the same connection by comparing ids.
The third test also submits with {Enter} from the password field instead of clicking the button. Pressing Enter in a text field submits the form, and many people sign up that way.
Check it worked
The summary shows 2 passed files and 7 passed tests. Nothing in the test files mentions a CSS class or the error paragraphs' ids by name; every lookup is by role, label or visible text.
Step 5 · Mock fetch with vi.fn
A valid form calls fetch. Unit tests should not depend on a real server, so replace the global fetch with a mock. vi.fn creates a function that records every call and returns whatever you tell it to. vi.stubGlobal puts it in place of fetch, and vi.unstubAllGlobals restores the original after each test.
cd ~/signup-tests-demo
cat > test/submit.test.js <<'JS'
import { afterEach, describe, expect, it, vi } from 'vitest';
import { screen, waitFor } from '@testing-library/dom';
import { renderSignupForm } from './render-form.js';
import { messages } from '../src/signup.js';
afterEach(() => {
vi.unstubAllGlobals();
});
async function fillValidForm(user) {
await user.type(screen.getByRole('textbox', { name: 'Email' }), ' ada@example.com ');
await user.type(screen.getByLabelText('Password'), 'correct horse');
await user.click(screen.getByRole('button', { name: 'Create account' }));
}
describe('submitting', () => {
it('does not call the server when the form is invalid', async () => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
const { user } = renderSignupForm();
await user.click(screen.getByRole('button', { name: 'Create account' }));
expect(fetchMock).not.toHaveBeenCalled();
});
it('sends trimmed details as JSON and confirms', async () => {
const fetchMock = vi.fn(async () => new Response(null, { status: 201 }));
vi.stubGlobal('fetch', fetchMock);
const { user } = renderSignupForm({ endpoint: '/api/accounts' });
await fillValidForm(user);
await waitFor(() => {
expect(screen.getByRole('status').textContent).toBe(messages.created);
});
expect(fetchMock).toHaveBeenCalledTimes(1);
const [url, options] = fetchMock.mock.calls[0];
expect(url).toBe('/api/accounts');
expect(options.method).toBe('POST');
expect(JSON.parse(options.body)).toEqual({ email: 'ada@example.com', password: 'correct horse' });
expect(screen.getByRole('textbox', { name: 'Email' }).value).toBe('');
});
it('puts a taken email back on the email field', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(null, { status: 409 })));
const { user } = renderSignupForm();
await fillValidForm(user);
const email = await screen.findByRole('textbox', {
name: 'Email',
description: messages.emailTaken,
});
expect(document.activeElement).toBe(email);
});
it('tells the person when the connection fails', async () => {
vi.stubGlobal('fetch', vi.fn(async () => {
throw new TypeError('Failed to fetch');
}));
const { user } = renderSignupForm();
await fillValidForm(user);
await waitFor(() => {
expect(screen.getByRole('status').textContent).toBe(messages.offline);
});
expect(screen.getByRole('button', { name: 'Create account' }).disabled).toBe(false);
});
});
JS
npx vitest runThe fetch promise resolves after the click has returned, so the status text appears a moment later. waitFor retries its callback until it stops throwing, for up to a second by default, and findByRole is the same idea wrapped in a query. Use them for anything that happens after a promise. Never add fixed sleeps.
The spaces around ada@example.com show less than they seem to. The HTML spec's value sanitisation for type="email" already strips leading and trailing whitespace, so in a real browser the field's value has no spaces by the time .trim() runs. Keep the .trim() as a cheap safety net, and remember that a test DOM only proves your own code's behaviour, not every browser rule.
The last test covers what a reader on a weak connection actually meets. The mock throws the same TypeError a browser throws when the request never reaches the server, and the test checks that the button is usable again so the person can retry.
Check it worked
The summary shows 3 passed files and 11 passed tests. Change status: 201 in the second test to status: 500 and run again: that test fails, and the error shows the received text was the server error message. Change it back.
Step 6 · Prove the suite catches a silent error
A test suite is only as good as the bugs it catches. Break the link between inputs and their errors, the kind of change that slips through a refactor because the page still looks right. Back up the module, then remove the one line in showError that calls linkDescription:
cd ~/signup-tests-demo
cp src/signup.js src/signup.js.orig
node -e "const fs = require('node:fs'); const f = 'src/signup.js'; fs.writeFileSync(f, fs.readFileSync(f, 'utf8').replace(' linkDescription(input, error.id);\n', ''));"
grep -c '^ linkDescription(' src/signup.js || trueThe errors still appear on screen. A sighted user would notice nothing. A screen reader user would hear only "Email, edit text, invalid entry" and no reason. Run the suite and expect it to fail:
cd ~/signup-tests-demo
if npx vitest run; then
echo "The suite passed, so it did not catch the broken error link"
false
else
echo "The suite failed, as it should"
fiPut the original back and run the suite again:
cd ~/signup-tests-demo
mv src/signup.js.orig src/signup.js
npx vitest runCheck it worked
grep -c prints 0, so the call is gone (unlinkDescription in clearError is untouched). The broken run reports 4 failed tests across validation.test.js and submit.test.js. Most say they are unable to find an element with the role "textbox", the name "Email" and the expected description; the password test shows the error id missing from aria-describedby. The next line reads The suite failed, as it should. After restoring the file, all 11 tests pass again.
Step 7 · Use watch mode and measure coverage
While you are working, leave Vitest running. In an interactive terminal, npm test (which runs vitest) starts watch mode: it runs the suite, then reruns only the tests affected each time you save a file.
cd ~/signup-tests-demo
npm testEdit a message in src/signup.js and save. The affected tests rerun within a second or so. Press h to see the keyboard shortcuts and q to quit. In a CI service, or with npm run test:run, Vitest runs once and exits instead.
Coverage shows which lines and branches the tests ran. Install the V8 coverage provider at the same version as Vitest, then replace the config with one that measures src and fails the run if coverage drops:
cd ~/signup-tests-demo
npm install --save-dev @vitest/coverage-v8@5.1.1
cat > vite.config.js <<'JS'
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'happy-dom',
coverage: {
provider: 'v8',
include: ['src/**/*.js'],
reporter: ['text', 'html'],
thresholds: {
lines: 90,
branches: 85,
},
},
},
});
JS
npx vitest run --coverage
ls coverage/index.htmlinclude limits the report to your source, not the tests. The thresholds make vitest run --coverage exit with an error if line coverage falls below 90 per cent or branch coverage below 85, so a pull request that adds untested code fails in CI. Treat the numbers as a floor, not a goal: the announcement test you broke in the last step matters more than any percentage.
Check it worked
After the test summary, a table lists signup.js with columns % Stmts, % Branch, % Funcs and % Lines, and the command exits without a threshold error. ls finds coverage/index.html. Open it in a browser to see each line of signup.js marked as run or not run. The one branch left uncovered is the 500 response: add a test for it, using the 409 test as a model, and watch the branch figure rise.
Step 8 · Clean up
Remove the demo folder. It holds everything this tutorial installed, including the coverage report.
cd ~
rm -rf ~/signup-tests-demoCheck it worked
ls ~/signup-tests-demo reports that there is no such file or directory.
Next steps
- Run user journeys in real Chromium and Firefox, with role-based locators like the ones here and a mocked API, in write end-to-end browser tests with Playwright.
- Compare the browser's built-in validation with the custom messages here in validate a form with the constraint validation API.
- Test code that has no DOM with no dependencies at all in write tests with the Node.js test runner.
Part of these paths
Related tutorials
- Write your first JavaScript tests with the built-in Node.js test runnerYou will write a small price module in JavaScript, cover it with six passing tests using node:test and node:assert, and know how to read a failure and run one test on its own, with no packages installed.
- Validate a form in JavaScript with the Constraint Validation APIYou will turn an HTML sign-up form into one that writes its own error messages with the Constraint Validation API, checks fields as people leave them, sends with fetch and gives the same accessible errors from the server when JavaScript is off.
- Write end-to-end browser tests with PlaywrightYou will have a Playwright suite that starts a Vite shop with vite preview, tests its sign-in and checkout journeys in headless Chromium and Firefox with role-based locators and a mocked API, and leaves a trace you can open when a test fails.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials