Testing the MERN App
By the end of this lesson one command, npm test, will check both halves of TaskBoard in under a minute. The server tests send real HTTP requests to the Express app, with a private in-memory MongoDB that starts empty for every test. The client tests render React components in a simulated browser and click them like a user. Together they prove the rules this course built: who may log in, who may change which task, which files are accepted, and what the screens show.
What you should know first: every earlier lesson, especially Authentication with JWT & Cookies and File Uploads & Images, because those rules are what we test. Test basics are taught in Testing with node:test and Testing with Vitest. Versions checked: Vitest 5.1.0, Supertest 7.3.2, mongodb-memory-server 11.3.0 (running MongoDB 9.0.4), @testing-library/react 16.3.3, @testing-library/user-event 14.6.12 and @testing-library/jest-dom 7.0.1. Every output below comes from a real run.
What to test, and where
Think of the checks a new Vande Bharat train gets before service. Engineers test single parts on a bench, run whole coaches on a test track, and only then take a few trial runs on the real line. Software tests come in the same three sizes:
| Kind | TaskBoard example | Speed | How many |
|---|---|---|---|
| Unit test: one function | validateTask in taskRules.js | Milliseconds | Many |
| Integration test: several parts together | POST /api/tasks/:id/attachments through Express, multer, Mongoose and the disk | About a second | Quite a few |
| End-to-end test: the real app in a browser | Log in, open a task, upload a photo | Several seconds | A handful |
This lesson covers the first two, which catch most bugs for little effort. End-to-end tools such as Playwright drive a real browser; they suit a few critical journeys.
We use Vitest for both halves. It already understands the client's Vite setup, and it runs plain Node.js code too, so the project needs one test runner and one set of commands. The built-in node:test runner would also work for the server.
Step 1: Install
From the top folder:
npm install -D vitest supertest mongodb-memory-server -w server
npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom -w client- Supertest sends HTTP requests to an Express
appobject without opening a port. - mongodb-memory-server downloads a real MongoDB binary once (it is cached afterwards) and starts a private copy for the tests, so they never touch your development data.
- jsdom imitates a browser page inside Node.js; React Testing Library renders components into it and finds elements the way a user would.
Add "test": "vitest run" to the scripts in both server/package.json and client/package.json, and "test": "npm test --workspaces" to the top-level package.json.
Step 2: A test database for the server
Remember why Build a REST API with Express 5 split app.js from server.js? This is the payoff. Tests import app and never call listen() or connectDB().
config.js refuses to load without its environment variables, so give the tests their own values in server/vitest.config.js:
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node",
setupFiles: ["./test/setup.js"],
hookTimeout: 60_000, // the first run downloads a MongoDB binary
// Test-only settings: config.js reads them, as it reads .env in development.
env: {
CLIENT_ORIGIN: "http://localhost:5173",
MONGODB_URI: "mongodb://replaced-by-test-setup",
JWT_SECRET: "test-only-secret-that-is-at-least-32-characters",
},
},
});The test secret is fake and only for tests; it never protects real data. server/test/setup.js runs before every test file:
// Runs before each test file: a private, in-memory MongoDB and an empty uploads folder.
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import mongoose from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";
import { afterAll, beforeAll, beforeEach } from "vitest";
import { config } from "../src/config.js";
let mongod;
beforeAll(async () => {
mongod = await MongoMemoryServer.create({ binary: { version: "9.0.4" } });
await mongoose.connect(mongod.getUri("taskboard-test"));
config.uploadDir = await fs.mkdtemp(path.join(os.tmpdir(), "taskboard-uploads-")); // one folder per test file
});
beforeEach(async () => {
// Every test starts with empty collections, so tests cannot depend on each other.
const collections = Object.values(mongoose.connection.collections);
await Promise.all(collections.map((c) => c.deleteMany({})));
});
afterAll(async () => {
await mongoose.disconnect();
await mongod.stop();
await fs.rm(config.uploadDir, { recursive: true, force: true });
});Vitest runs test files in parallel, so each file gets its own database server and its own temporary uploads folder. Changing config.uploadDir works because the controllers read it each time they save a file.
Step 3: Helpers, and a cookie surprise
server/test/helpers.js creates the two staff members with one task each, and logs in:
import request from "supertest";
import { app } from "../src/app.js";
import { Task, User } from "../src/models/index.js";
import { hashPassword } from "../src/utils/passwords.js";
export const PASSWORD = "test-password-123";
export async function makeUsers() {
const passwordHash = await hashPassword(PASSWORD);
const [priya, kabir] = await User.create([
{ name: "Priya Sharma", email: "priya@example.com", role: "teacher", passwordHash },
{ name: "Kabir Malik", email: "kabir@example.com", role: "admin", passwordHash },
]);
const priyaTask = await Task.create({ title: "Print Class 10 maths worksheets", assignee: priya._id });
const kabirTask = await Task.create({ title: "Call parents about Sunday test", assignee: kabir._id });
return { priya, kabir, priyaTask, kabirTask };
}
// Logs in and returns the "token=..." cookie to send with later requests.
export async function loginAs(email) {
const res = await request(app).post("/api/auth/login").send({ email, password: PASSWORD }).expect(200);
return res.headers["set-cookie"][0].split(";")[0];
}Why copy the cookie by hand? Supertest has request.agent(app), which stores cookies like a browser. We tried it first: login returned 200, but the next GET /api/auth/me returned 401 "Please log in". TaskBoard's cookie is Secure, and Supertest talks plain HTTP, so the agent correctly refused to send it back. Reading Set-Cookie and sending Cookie ourselves keeps the real security settings in the code under test. Never weaken Secure just to make a test pass.
Step 4: API tests
Each test is a short story: arrange the data, act with a request, assert on the reply and the database. server/test/tasks.test.js:
import request from "supertest";
import { beforeEach, describe, expect, it } from "vitest";
import { app } from "../src/app.js";
import { Task } from "../src/models/index.js";
import { loginAs, makeUsers } from "./helpers.js";
describe("tasks", () => {
let data;
let priya;
beforeEach(async () => {
data = await makeUsers();
priya = await loginAs("priya@example.com");
});
it("refuses every task route without a login", async () => {
await request(app).get("/api/tasks").expect(401);
});
it("reports every invalid field at once", async () => {
const res = await request(app)
.post("/api/tasks")
.set("Cookie", priya)
.send({ title: "", dueDate: "next Friday" })
.expect(400);
expect(res.body.error.details.map((d) => d.field)).toEqual(["title", "dueDate"]);
});
it("lets a teacher move her own task but not someone else's", async () => {
await request(app).patch(`/api/tasks/${data.priyaTask.id}`).set("Cookie", priya).send({ status: "doing" }).expect(200);
const res = await request(app)
.patch(`/api/tasks/${data.kabirTask.id}`)
.set("Cookie", priya)
.send({ status: "done" })
.expect(403);
expect(res.body.error.message).toBe("You can only change tasks assigned to you");
expect((await Task.findById(data.kabirTask.id)).status).toBe("todo"); // unchanged in the database
});
it("lets only an admin delete", async () => {
await request(app).delete(`/api/tasks/${data.priyaTask.id}`).set("Cookie", priya).expect(403);
const kabir = await loginAs("kabir@example.com");
await request(app).delete(`/api/tasks/${data.priyaTask.id}`).set("Cookie", kabir).expect(204);
expect(await Task.exists({ _id: data.priyaTask.id })).toBeNull();
});
});Notice the last line of the ownership test. Checking only the 403 would miss a bug where the server refuses after saving. Asking the database proves nothing changed.
server/test/auth.test.js checks that a wrong password and an unknown email get the same reply, that the cookie has HttpOnly; Secure; SameSite=Strict, and that passwordHash never appears. server/test/attachments.test.js uploads with Supertest's .attach():
// The 8-byte PNG signature is enough for file-type to recognise a PNG.
const PNG_BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0x0d, 0x49, 0x48, 0x44, 0x52]);
it("refuses a text file that pretends to be a PNG", async () => {
const fake = Buffer.from("<script>alert(1)");
const res = await request(app).post(url).set("Cookie", priya).attach("file", fake, "marks.png").expect(415);
expect(res.body.error.details[0].field).toBe("file");
});
it("refuses files over 2 MB", async () => {
const big = Buffer.concat([PNG_BYTES, Buffer.alloc(2 * 1024 * 1024)]);
const res = await request(app).post(url).set("Cookie", priya).attach("file", big, "scan.png").expect(413);
expect(res.body.error.message).toBe("File is too large (limit 2 MB)");
});Two more attachment tests store a real PNG (checking the reply has no storedName, the file is on disk, and the download has Content-Disposition: attachment) and confirm a visitor without a cookie gets 401. Run them:
npm test -w serverRUN v5.1.0 C:/Users/meera/code/taskboard/server
Test Files 3 passed (3)
Tests 11 passed (11)
Start at 18:14:40
Duration 35.97s (import 41%, setup 36%, tests 21%, transform 2%)The time goes on loading modules, starting three MongoDB servers, and Argon2 hashing, which is slow on purpose. That is still far faster than checking eleven rules by hand.
Step 5: Watch a test catch a bug
A test you have never seen fail proves little. So we "simplified" assertCanChange to if (user.role !== "admin"), a plausible mistake that locks teachers out of their own tasks. Three tests failed at once:
❯ test/attachments.test.js (4 tests | 2 failed)
× stores a real PNG under a random name and lets staff download it
× refuses a text file that pretends to be a PNG
❯ test/tasks.test.js (4 tests | 1 failed)
× lets a teacher move her own task but not someone else's
FAIL test/tasks.test.js > tasks > lets a teacher move her own task but not someone else's
Error: expected 200 "OK", got 403 "Forbidden"
❯ test/tasks.test.js:30:112For the failing tests, Vitest also printed the request log lines, such as PATCH /api/tasks/6afaf96dc02a3ee8cdd36c63 403 21.7ms, which made the cause obvious. We restored the line and all tests passed again.
Step 6: Client tests with React Testing Library
Add a test block to client/vite.config.js, and import defineConfig from vitest/config so the editor knows about it:
import react from "@vitejs/plugin-react";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [react()],
server: { port: 5173, proxy: { "/api": "http://localhost:4000" } },
test: {
environment: "jsdom",
setupFiles: ["./src/test/setup.js"],
},
});client/src/test/setup.js adds readable checks such as toBeInTheDocument() and cleans up after each test:
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
afterEach(cleanup); // remove what each test renderedThe most valuable client test checks the API contract from the React side: a server error with details must land next to the right field. TaskForm takes onSubmit as a prop, so the test passes a fake function, a mock, that rejects with a real ApiError. No network is involved. client/src/components/TaskForm.test.jsx:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { ApiError } from "../api/client.js";
import TaskForm from "./TaskForm.jsx";
const users = [{ id: "u1", name: "Priya Sharma" }, { id: "u9", name: "Rohan Verma" }];
describe("TaskForm", () => {
it("does not call onSubmit when the title is empty", async () => {
const onSubmit = vi.fn();
render(<TaskForm users={users} submitLabel="Create task" onSubmit={onSubmit} />);
await userEvent.click(screen.getByRole("button", { name: "Create task" }));
expect(screen.getByText("Title is required")).toBeInTheDocument();
expect(screen.getByLabelText("Title")).toHaveFocus();
expect(onSubmit).not.toHaveBeenCalled();
});
it("puts the server's field message next to the right field", async () => {
const onSubmit = vi.fn().mockRejectedValue(
new ApiError(400, "Validation failed", [{ field: "assignee", message: "No user with this id" }])
);
render(<TaskForm users={users} submitLabel="Create task" onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText("Title"), "Book hall for parent meeting");
await userEvent.selectOptions(screen.getByLabelText("Assigned to"), "Rohan Verma");
await userEvent.click(screen.getByRole("button", { name: "Create task" }));
expect(onSubmit).toHaveBeenCalledWith({ title: "Book hall for parent meeting", dueDate: "", assignee: "u9" });
expect(await screen.findByText("No user with this id")).toBeInTheDocument();
expect(screen.getByLabelText("Assigned to")).toHaveAttribute("aria-invalid", "true");
expect(screen.getByRole("alert")).toHaveTextContent("Please fix the marked fields.");
});
});The test finds elements by role and label, as a screen reader does, never by CSS class. That makes it a free accessibility check too: if the label and input lose their link, getByLabelText fails.
RequireAuth.test.jsx renders the guard inside a MemoryRouter, a router that keeps its address in memory, and supplies the auth state through <AuthContext value={...}>. Three tests check the three states: "Checking your session...", a redirect to the login page, and the page itself. taskRules.test.js checks the pure functions, including that 120 characters pass and 121 fail, the same limit as the server. From the top folder, npm test runs everything (output shortened):
> client@0.0.0 test
> vitest run
Test Files 3 passed (3)
Tests 8 passed (8)
> test
> vitest run
Test Files 3 passed (3)
Tests 11 passed (11)See a test runner work
A test runner is not magic. This small one shows the idea in the browser: each test calls the code and compares the result, and a "bug" button breaks the function so you can watch the tests fail.
import { useState } from "react";
import { createRoot } from "react-dom/client";
function makeValidateTask(buggy) {
return (values) => {
const errors = {};
const title = buggy ? values.title : values.title.trim(); // the bug: forgets to trim
if (!title) errors.title = "Title is required";
else if (title.length > 120) errors.title = "Title must be 120 characters or fewer";
return errors;
};
}
function expectEqual(actual, expected) {
const a = JSON.stringify(actual), e = JSON.stringify(expected);
if (a !== e) throw new Error(`expected ${e}, got ${a}`);
}
const TESTS = [
["needs a title", (v) => expectEqual(v({ title: "" }), { title: "Title is required" })],
["treats spaces as empty", (v) => expectEqual(v({ title: " " }), { title: "Title is required" })],
["accepts 120 characters", (v) => expectEqual(v({ title: "a".repeat(120) }), {})],
["refuses 121 characters", (v) => expectEqual(v({ title: "a".repeat(121) }).title, "Title must be 120 characters or fewer")],
];
function Runner() {
const [buggy, setBuggy] = useState(false);
const validate = makeValidateTask(buggy);
const results = TESTS.map(([name, test]) => {
try { test(validate); return { name, ok: true }; }
catch (err) { return { name, ok: false, why: err.message }; }
});
const failed = results.filter((r) => !r.ok).length;
return (
<div>
<label><input type="checkbox" checked={buggy} onChange={(e) => setBuggy(e.target.checked)} /> introduce the bug</label>
<ul>{results.map((r) => <li key={r.name} style={{ color: r.ok ? "green" : "crimson" }}>{r.ok ? "✓" : "×"} {r.name}{r.why && `: ${r.why}`}</li>)}</ul>
<p><strong>Tests {results.length - failed} passed, {failed} failed</strong></p>
</div>
);
}
createRoot(document.getElementById("root")).render(<Runner />);All four pass at first. Tick "introduce the bug": "treats spaces as empty" turns red with expected {"title":"Title is required"}, got {}. Only one test catches it, which is why each rule deserves its own small test.
The second demo shows why finding elements by label doubles as an accessibility check. The "test" looks for the box labelled "Title", as getByLabelText does. Untick the link between label and input, a common mistake, and the lookup fails.
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
// Like getByLabelText: find the label by its text, then the control it points to.
function getByLabelText(root, text) {
const label = [...root.querySelectorAll("label")].find((l) => l.textContent.trim() === text);
if (!label) throw new Error(`no label with text "${text}"`);
const control = label.htmlFor ? root.querySelector(`#${label.htmlFor}`) : label.querySelector("input, select, textarea");
if (!control) throw new Error(`label "${text}" is not linked to any input`);
return control;
}
function Demo() {
const [linked, setLinked] = useState(true);
const [result, setResult] = useState("");
useEffect(() => {
try {
const box = getByLabelText(document.getElementById("form-under-test"), "Title");
setResult(`found <${box.tagName.toLowerCase()} id="${box.id}">: test passes`);
} catch (err) {
setResult(`test fails: ${err.message}`);
}
}, [linked]);
return (
<div>
<p><label><input type="checkbox" checked={linked} onChange={(e) => setLinked(e.target.checked)} /> label is linked to the input</label></p>
<div id="form-under-test">
<label htmlFor={linked ? "title" : "titel"}>Title</label> <input id="title" />
</div>
<p><strong>{result}</strong></p>
</div>
);
}
createRoot(document.getElementById("root")).render(<Demo />);With the box ticked, the result reads found <input id="title">: test passes. Untick it and htmlFor points at a misspelt id: the test fails, and so would a screen reader trying to name the input.
Common mistakes
- Testing against your development database. Tests delete data. Use mongodb-memory-server or a separate test database.
- Tests that depend on each other's data. Empty the collections before each test so any test can run alone.
- Turning off
SecureorrequireAuthto make tests easier. Then you are testing a different app. Send the real cookie. - Checking only the status code. Also check the body and, for refusals, that the database did not change.
- Finding elements by CSS class. Use roles and labels; tests then match what users and screen readers see.
- Never seeing a test fail. Break the code once on purpose to prove the test can catch the bug.
Interview questions
1. How do you test an Express API without starting the server on a port?
Export the app from one module and call listen() in another. Supertest accepts the app object, starts it on a temporary internal connection, and lets you chain requests and assertions such as .expect(201).
2. Why use mongodb-memory-server instead of mocking Mongoose?
It runs a real MongoDB, so unique indexes, validation, queries and populate behave exactly as in production. Mocks only repeat what you think the database does. Each test file gets a fresh, isolated database that is thrown away afterwards.
3. What is React Testing Library's guiding idea?
Test components the way users use them: render, find elements by role, label or text, interact with user-event, and assert on what is visible. Avoid testing internal state or implementation details, so refactoring does not break tests that still describe correct behaviour.
4. What would you test first in a MERN app with no tests?
The rules that would hurt most if broken: authentication, authorisation and validation on the API, because the client cannot enforce them. Then the main form flows on the client, including how server errors are shown. A few end-to-end tests can cover the most important user journeys.
Key points
- Vitest runs both halves;
npm testat the top runs the client and server suites. - Supertest sends requests to the exported
app; no port and noconnectDB()in tests. - mongodb-memory-server gives each test file a private MongoDB; collections are emptied before every test.
- Send the real
Securecookie by hand; Supertest's agent will not return it over plain HTTP. - Assert on status, body and database state, and break the code once to see each test fail.
- React Testing Library finds elements by role and label; mock props such as
onSubmitto test server error handling without a network.
Exercise
Add a server test: Priya tries to attach a valid PNG to Kabir's task. Assert that the reply is 403, that Kabir's task still has no attachments in the database, and that the test's uploads folder is still empty.
Show solution
// server/test/exercise.test.js
import fs from "node:fs/promises";
import request from "supertest";
import { expect, it } from "vitest";
import { app } from "../src/app.js";
import { config } from "../src/config.js";
import { Task } from "../src/models/index.js";
import { loginAs, makeUsers } from "./helpers.js";
it("does not let a teacher attach files to someone else's task", async () => {
const { kabirTask } = await makeUsers();
const priya = await loginAs("priya@example.com");
const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
await request(app)
.post(`/api/tasks/${kabirTask.id}/attachments`)
.set("Cookie", priya)
.attach("file", png, "photo.png")
.expect(403);
expect((await Task.findById(kabirTask.id)).attachments).toHaveLength(0);
expect(await fs.readdir(config.uploadDir)).toEqual([]);
});Test Files 1 passed (1)
Tests 1 passed (1)The empty-folder check matters: it proves the permission check runs before the file is written, not after. If someone moved assertCanChange below fs.writeFile, the status would still be 403, but this assertion would fail.
Quick Quiz
1. Why do TaskBoard's tests import app from app.js instead of starting server.js?
Splitting the app from the listener makes it testable.
2. Supertest's request.agent(app) did not send TaskBoard's login cookie back. Why?
Agents follow cookie rules; sending the cookie header by hand keeps the real security settings.
3. In the ownership test, why also check the task's status in the database?
A status code alone cannot show that nothing was saved.
4. Which query best matches how users find the title box in React Testing Library?
Labels and roles are what people and assistive technology use.
Learn MERN Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
