How to Write Unit Tests for a Web App
In this article
To write unit tests for a web app, you isolate the smallest pieces of your code—functions, methods, components—and verify each one's behavior with automated checks that run fast and independently. Start by choosing a test runner and assertion library for your stack, then write tests for pure logic first, mock external dependencies, and run the suite on every change. This guide walks through the practical steps, from setup to maintenance, and covers common pitfalls and troubleshooting.
What You'll Need
- A web app codebase with a clear separation between business logic and framework code (e.g., utility functions, services, components).
- A test runner and assertion library compatible with your language and framework—for JavaScript/TypeScript, Jest, Vitest, or Mocha with Chai are common; for Python, pytest; for Ruby, RSpec; for Java, JUnit.
- A mocking or stubbing library (often included in the test runner) to replace network calls, databases, and other external services.
- Node.js and a package manager (npm, yarn, or pnpm) if you're testing a JavaScript-based app.
- A code editor and a terminal.
Step-by-Step
- Set up the test environment. Install your chosen test runner and configure it to find test files (commonly named
*.test.jsor*.spec.js). Add a script topackage.jsonsuch as"test": "jest"so you can run tests withnpm test. If you're using a framework like React, include any necessary transformers (e.g., Babel or SWC) so JSX and modern syntax work. - Identify units to test. Focus on pure functions, utility modules, and isolated component logic—anything that takes input and returns output without side effects. Avoid testing framework internals or third-party libraries. A good rule: if a function has branching logic (if/else, loops, error handling), it deserves tests.
- Write your first test for a pure function. Create a test file next to the module or in a
__tests__folder. Use a describe block to group related tests and an it (or test) block for each case. For example:
Run the test to confirm it passes.// math.test.js import { add } from './math'; describe('add', () => { it('returns the sum of two numbers', () => { expect(add(2, 3)).toBe(5); }); }); - Cover edge cases and error paths. Add tests for zero, negative numbers, empty strings, null/undefined inputs, and expected exceptions. For instance, test that a validation function throws a specific error when given invalid data. This builds confidence that your code handles real-world messiness.
- Mock external dependencies. When a unit calls an API, reads from a database, or uses a browser API like
localStorage, replace those with mocks or stubs. In Jest, usejest.mock('./api')orjest.spyOn. This keeps tests fast, deterministic, and isolated—no network required. - Test components in isolation (for UI frameworks). Use a testing library like React Testing Library or Vue Test Utils to render a component with specific props and assert on the output. Avoid testing implementation details (like internal state) and focus on what the user sees: text, roles, and event handlers. Mock child components if they're complex.
- Run tests frequently and automate. Execute your test suite locally before committing. Set up a pre-commit hook or a CI pipeline (e.g., GitHub Actions) to run tests on every push. This catches regressions early and enforces a baseline of quality.
- Measure coverage and fill gaps. Use built-in coverage tools (e.g.,
jest --coverage) to see which lines and branches are untested. Aim for meaningful coverage of critical logic, not 100% everywhere. Add tests for uncovered error handlers and edge cases you missed. - Refactor tests for readability and maintainability. Use descriptive test names (e.g., "returns 400 when email is missing"), extract repeated setup into helper functions or
beforeEachblocks, and avoid logic in tests. A test should read like a specification. - Keep tests fast and independent. Each test should run in isolation—no shared state between tests. Use
beforeEachto reset mocks and databases. If a test takes more than a few hundred milliseconds, consider whether it's truly a unit test or an integration test that belongs in a separate suite.
Common Mistakes
- Testing implementation details. Asserting on internal state or private methods makes tests brittle; refactoring breaks them even when behavior is unchanged. Test public behavior instead.
- Not mocking external services. Hitting a real API or database in unit tests leads to slow, flaky tests that fail when the network is down.
- Writing tests after the code is "done" and skipping edge cases. Tests written as an afterthought often miss error paths and boundary conditions.
- Over-mocking. Mocking everything can hide integration issues; use integration tests for wiring and unit tests for logic.
- Ignoring test failures. A failing test is a signal—fix the code or the test, but never commit a red suite.
Tips
- Follow the Arrange-Act-Assert pattern: set up the inputs, call the function, then check the output.
- Use test.each or parameterized tests to cover multiple input/output pairs without duplication.
- Keep test files close to the code they test (e.g.,
math.test.jsnext tomath.js) for easy discovery. - Run tests in watch mode during development to get instant feedback.
- Treat test code with the same care as production code—refactor and review it.
Troubleshooting
If tests fail unexpectedly, first check that mocks are reset between tests—stale mock state is a common culprit. Use jest.clearAllMocks() in a beforeEach block. If a test passes locally but fails in CI, ensure the CI environment has the same Node version and dependencies (use a lockfile). For asynchronous tests, make sure you're awaiting promises or using done correctly; a missing await can cause false positives. If coverage reports show lines as uncovered that you believe are tested, check that the test runner is configured to collect coverage from the right files. When a test is flaky, isolate it by running it alone with --testNamePattern; if it passes alone but fails in the suite, there's likely shared state or a timing issue. Finally, if you're stuck on a failing assertion, log the actual value (e.g., console.log(result)) to compare with the expected.
Frequently Asked Questions
Do I need to test every function?
No. Focus on functions with logic, edge cases, or that are critical to the app. Trivial getters or framework-generated code can be skipped.
How many unit tests should I write?
Enough to cover the behavior you care about—typically one or more per branch and edge case. Quality matters more than quantity.
Can I use the same test runner for frontend and backend?
Often yes, if you're using JavaScript/TypeScript. Jest and Vitest work for both Node.js and browser code with proper configuration.
What's the difference between unit tests and integration tests?
Unit tests isolate a single unit (function, component) and mock dependencies. Integration tests combine units and may use real databases or APIs to verify they work together.
How do I test code that relies on the current date?
Mock the date library or use fake timers (e.g., jest.useFakeTimers()) to set a fixed time, making tests deterministic.
Should I test private methods?
Generally no—test them indirectly through public methods. If a private method is complex, consider extracting it into its own module and testing that.