Jest and Vitest: Matchers, Mocks, Spies, Snapshots and Coverage
Jest has been the most popular JavaScript test framework for years, and Vitest is its fast, modern successor with an almost identical API. Most JavaScript job descriptions mention one of them, front-end projects use them for component and unit tests, and their expect style is the same one Playwright uses for its assertions. In this lesson you will set up both, write tests with the expect matchers, run data-driven tests with test.each, replace dependencies with mocks and spies, mock whole modules, control time, and use snapshots and coverage. Every terminal output was captured from real runs (Jest 30, Vitest 5, Node.js 26) in a Windows terminal, where Jest prints √ where macOS and Linux show ✓.
📖 What You’ll Learn: what Jest and Vitest are and how they differ from node:test, installing and running each, describe/test/it, the expect matchers (toBe, toEqual, toContain, toMatch, toThrow, resolves/rejects), test.each, setup and teardown hooks, mock functions (jest.fn / vi.fn) and their assertions, mockReturnValue and mockResolvedValue, spies (spyOn), mocking whole modules, fake timers, snapshots, coverage reports, reading failure output, and choosing between Jest, Vitest and node:test.
🃏 Jest, Vitest and node:test
| Jest | Vitest | node:test | |
|---|---|---|---|
| Install | npm i -D jest | npm i -D vitest | Built into Node.js |
| Assertions | expect(x).toBe(y) | Same expect API | assert.equal(x, y) |
| Mocks | jest.fn, jest.mock | vi.fn, vi.mock | mock.fn, mock.method |
| ES modules / TypeScript | Needs configuration or Babel | Works out of the box (Vite) | Native ESM; type stripping |
| Speed | Good | Very fast, great watch mode | Fast, no dependencies |
| Typical home | React apps, older projects | Vite, Vue, Svelte and new projects | Libraries, scripts, Node.js tools |
The test code itself is almost identical in Jest and Vitest, so learning one teaches you the other. The expect(...).toXxx() style is also what Playwright Test uses, with extra web-first matchers such as toBeVisible().
⬇️ Setting Up and Running Jest
⌨️ Terminal
npm init -y
npm install -D jest
npm pkg set scripts.test=jest
Jest finds files named *.test.js or *.spec.js, or anything in a __tests__ folder. Here is the code under test and its tests:
📄 src/cart.js
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
function applyCoupon(total, code) {
if (code === "SQA10") return total * 0.9;
if (code === "FLAT100") return Math.max(total - 100, 0);
throw new Error(`Invalid coupon: ${code}`);
}
module.exports = { calculateTotal, applyCoupon };
📄 src/cart.test.js
const { calculateTotal, applyCoupon } = require("./cart");
describe("calculateTotal", () => {
test("adds price × qty for every item", () => {
const items = [{ price: 499, qty: 2 }, { price: 799, qty: 1 }];
expect(calculateTotal(items)).toBe(1797);
});
test("returns 0 for an empty cart", () => {
expect(calculateTotal([])).toBe(0);
});
});
describe("applyCoupon", () => {
test.each([
["SQA10", 1000, 900],
["FLAT100", 1000, 900],
["FLAT100", 50, 0],
])("%s on %i gives %i", (code, total, expected) => {
expect(applyCoupon(total, code)).toBe(expected);
});
test("rejects an unknown coupon", () => {
expect(() => applyCoupon(1000, "FREE")).toThrow("Invalid coupon: FREE");
});
});
⌨️ Terminal
npx jest --verbose src/cart.test.js
🖥️ Output (Windows terminal, excerpt)
PASS src/cart.test.js
calculateTotal
√ adds price × qty for every item (5 ms)
√ returns 0 for an empty cart
applyCoupon
√ SQA10 on 1000 gives 900 (1 ms)
√ FLAT100 on 1000 gives 900
√ FLAT100 on 50 gives 0
√ rejects an unknown coupon (6 ms)
test.each turns a table of cases into one test each, and the %s/%i placeholders put the values into the test names. Run npx jest --watch to re-run tests automatically as you edit.
✅ The expect Matchers
| Matcher | Checks |
|---|---|
toBe(x) | Same primitive value / same object reference (Object.is) |
toEqual(obj) | Same content, recursively (ignores undefined properties) |
toStrictEqual(obj) | Same content and same types, undefined properties included |
toBeTruthy() / toBeFalsy() / toBeNull() / toBeUndefined() | Truthiness and empty values |
toBeGreaterThan(n) / toBeCloseTo(0.3) | Numbers (toBeCloseTo for floating point) |
toContain(item) / toHaveLength(n) | Arrays and strings |
toMatch(/regex/) | Strings |
toHaveProperty("a.b", value) / toMatchObject({...}) | Part of an object |
toThrow("message") | A function throws (wrap the call: expect(() => fn())) |
await expect(p).resolves.toBe(x) / .rejects.toThrow() | Promises |
.not.toBe(x) | Negates any matcher |
⚠️ Watch out: expect(0.1 + 0.2).toBe(0.3) fails because of floating point; use toBeCloseTo(0.3). And toBe on two objects with the same content fails (different references); use toEqual.
When a check fails, Jest shows the expected and received values and points at the failing line. Here the 10% coupon was accidentally changed to 5%:
⌨️ Terminal
npx jest
🖥️ Output
FAIL src/cart.test.js
● applyCoupon › SQA10 on 1000 gives 900
expect(received).toBe(expected) // Object.is equality
Expected: 900
Received: 950
18 | ["FLAT100", 50, 0],
19 | ])("%s on %i gives %i", (code, total, expected) => {
> 20 | expect(applyCoupon(total, code)).toBe(expected);
| ^
21 | });
22 |
23 | test("rejects an unknown coupon", () => {
at toBe (src/cart.test.js:20:38)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 5 passed, 6 total
Snapshots: 0 total
Time: 1.512 s, estimated 2 s
Ran all test suites.
Hooks
beforeAll, afterAll, beforeEach and afterEach work like the node:test hooks: create fresh data in beforeEach, clean up mocks in afterEach, and start or stop expensive resources once in beforeAll/afterAll.
🎭 Mocks, Spies and Module Mocks
A unit test should not call a real API, send real emails or wait for real time. Jest replaces those dependencies:
| Tool | Does |
|---|---|
jest.fn() | A new mock function that records calls; configure with mockReturnValue, mockResolvedValue, mockImplementation |
jest.spyOn(obj, "method") | Watches (and optionally replaces) an existing method; mockRestore() puts the original back |
jest.mock("./module") | Replaces every export of a module with mock functions |
jest.useFakeTimers() | Controls setTimeout, setInterval and Date; advance with jest.advanceTimersByTime(ms) |
The service below calls an API module and sets a timer. The test mocks the API module, spies on Math.random and fast-forwards time:
📄 src/api.js
async function fetchUser(id) {
const res = await fetch(`https://api.example.com/users/${id}`);
return res.json();
}
module.exports = { fetchUser };
📄 src/userService.js
const api = require("./api");
async function getDisplayName(id) {
const user = await api.fetchUser(id);
if (!user) return "Unknown user";
return `${user.firstName} ${user.lastName}`.trim();
}
function notifyLater(callback, ms = 5000) {
setTimeout(() => callback("reminder sent"), ms);
}
module.exports = { getDisplayName, notifyLater };
📄 src/userService.test.js
const api = require("./api");
const { getDisplayName, notifyLater } = require("./userService");
jest.mock("./api"); // replace every export of ./api with a jest.fn()
afterEach(() => jest.clearAllMocks());
test("joins first and last name", async () => {
api.fetchUser.mockResolvedValue({ firstName: "Asha", lastName: "Rao" });
await expect(getDisplayName(7)).resolves.toBe("Asha Rao");
expect(api.fetchUser).toHaveBeenCalledTimes(1);
expect(api.fetchUser).toHaveBeenCalledWith(7);
});
test("handles a missing user", async () => {
api.fetchUser.mockResolvedValue(null);
expect(await getDisplayName(99)).toBe("Unknown user");
});
test("spyOn watches a real method", () => {
const spy = jest.spyOn(Math, "random").mockReturnValue(0.42);
expect(Math.random()).toBe(0.42);
expect(spy).toHaveBeenCalled();
spy.mockRestore();
});
test("fake timers run a 5 second reminder instantly", () => {
jest.useFakeTimers();
const callback = jest.fn();
notifyLater(callback);
expect(callback).not.toHaveBeenCalled();
jest.advanceTimersByTime(5000);
expect(callback).toHaveBeenCalledWith("reminder sent");
jest.useRealTimers();
});
⌨️ Terminal
npx jest --verbose src/userService.test.js
🖥️ Output (Windows terminal, excerpt)
PASS src/userService.test.js
√ joins first and last name (9 ms)
√ handles a missing user
√ spyOn watches a real method (1 ms)
√ fake timers run a 5 second reminder instantly (4 ms)
| Mock assertion | Checks |
|---|---|
toHaveBeenCalled() | Called at least once |
toHaveBeenCalledTimes(n) | Called exactly n times |
toHaveBeenCalledWith(a, b) | Called with these arguments (at least once) |
toHaveBeenLastCalledWith(...) | Arguments of the last call |
mockFn.mock.calls | Every call’s arguments, for custom checks |
💡 Tip: Call jest.clearAllMocks() (or set clearMocks: true in the config) between tests, otherwise call counts add up across tests and the second test sees calls from the first.
⚡ The Same Tests in Vitest
Vitest uses ES modules and imports its functions explicitly; jest.* becomes vi.*. Everything else reads the same:
⌨️ Terminal
npm init -y
npm pkg set type=module
npm install -D vitest
npm pkg set scripts.test="vitest run"
📄 src/userService.test.js (Vitest)
import { test, expect, vi, beforeEach } from "vitest";
import { getDisplayName } from "./userService.js";
import { fetchUser } from "./api.js";
vi.mock("./api.js", () => ({ fetchUser: vi.fn() })); // replace the module
beforeEach(() => vi.clearAllMocks());
test("joins first and last name", async () => {
vi.mocked(fetchUser).mockResolvedValue({ firstName: "Asha", lastName: "Rao" });
await expect(getDisplayName(7)).resolves.toBe("Asha Rao");
expect(fetchUser).toHaveBeenCalledWith(7);
});
test("compares objects with toEqual", () => {
const user = { name: "Asha", roles: ["tester"] };
expect(user).toEqual({ name: "Asha", roles: ["tester", "admin"] });
});
The second test fails on purpose, to show Vitest’s diff for objects:
⌨️ Terminal
npx vitest run
🖥️ Output (Windows terminal, divider lines shortened)
RUN v5.1.1 C:/Users/you/vitest-demo
✓ src/cart.test.js (5 tests) 16ms
❯ src/userService.test.js (2 tests | 1 failed) 33ms
✓ joins first and last name 9ms
× compares objects with toEqual 21ms
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
FAIL src/userService.test.js > compares objects with toEqual
AssertionError: expected { name: 'Asha', roles: [ 'tester' ] } to deeply equal { name: 'Asha', …(1) }
- Expected
+ Received
{
"name": "Asha",
"roles": [
"tester",
- "admin",
],
}
❯ src/userService.test.js:17:16
15| test("compares objects with toEqual", () => {
16| const user = { name: "Asha", roles: ["tester"] };
17| expect(user).toEqual({ name: "Asha", roles: ["tester", "admin"] });
| ^
18| });
19|
Test Files 1 failed | 1 passed (2)
Tests 1 failed | 6 passed (7)
Start at 21:20:58
Duration 561ms (transform 59%, import 23%, tests 14%, worker 4%)
| Jest | Vitest |
|---|---|
jest.fn() | vi.fn() |
jest.spyOn() | vi.spyOn() |
jest.mock("./m") (automock) | vi.mock("./m.js", () => ({ ... })) (factory) or automock |
jest.useFakeTimers() | vi.useFakeTimers() |
| Globals available automatically | Import from “vitest” (or set globals: true) |
jest --watch | vitest (watch is the default; vitest run runs once) |
📸 Snapshots and Coverage
toMatchSnapshot() stores the value the first time and compares on later runs. Jest writes it into a __snapshots__ folder:
📄 src/report.test.js
test("report matches the snapshot", () => {
expect(buildReport([{ name: "login", status: "passed" }, { name: "cart", status: "failed" }])).toMatchSnapshot();
});
📄 src/__snapshots__/report.test.js.snap (generated)
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`report matches the snapshot 1`] = `
{
"failed": [
"cart",
],
"total": 2,
}
`;
Update snapshots deliberately with npx jest -u (Vitest: vitest -u), and review the diff in the pull request. toMatchInlineSnapshot() writes the snapshot into the test file itself, which is easier to review for small values.
--coverage adds a table of covered statements, branches, functions and lines:
⌨️ Terminal
npx jest --coverage
🖥️ Output
----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------|---------|----------|---------|---------|-------------------
All files | 89.47 | 100 | 85.71 | 85.71 |
api.js | 33.33 | 100 | 0 | 33.33 | 2-3
cart.js | 100 | 100 | 100 | 100 |
userService.js | 100 | 100 | 100 | 100 |
----------------|---------|----------|---------|---------|-------------------
Test Suites: 3 passed, 3 total
Tests: 11 passed, 11 total
Snapshots: 1 passed, 1 total
Time: 3.243 s
Ran all test suites.
api.js shows low coverage because the tests mock it: the real fetch call is never executed. That is expected for a unit test; an integration or Playwright API test covers it. Vitest needs npm i -D @vitest/coverage-v8 before vitest run --coverage.
🧪 Tester Scenario: What to Mock and What Not To
| Mock it | Do not mock it |
|---|---|
| Network calls to other services | The function you are testing |
| Email, SMS, payments | Simple pure helpers it uses |
| Time, timers, random numbers | Data structures (arrays, Maps) |
| Slow resources (databases, file uploads) | Everything: a test that mocks every collaborator proves nothing |
Each unit test should answer one question: “given these inputs and these responses from dependencies, does my code do the right thing?” The integration between the real pieces is then covered by a smaller number of API and end-to-end tests, the subject of the next lesson.
- A failing mock-based test with a message like
Expected: 900, Received: 950is a precise bug report. - If a test needs ten mocks to run, the code under test probably does too much; that is useful feedback for developers.
- Snapshot and coverage numbers support reviews; they never replace thinking about the important cases.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Which matcher would you use to check that getUser() returns an object with name: "Asha" and active: true, ignoring other fields?
Show answer
expect(getUser()).toMatchObject({ name: "Asha", active: true }). toEqual would also compare all other fields.
Q2. Write a Jest test that checks applyCoupon(1000, "BAD") throws “Invalid coupon: BAD”.
Show answer
test("rejects a bad coupon", () => {
expect(() => applyCoupon(1000, "BAD")).toThrow("Invalid coupon: BAD");
});Note the arrow function: expect(applyCoupon(1000, "BAD")) would throw before Jest can catch it.
Q3. Convert this Jest mock to Vitest: const save = jest.fn().mockResolvedValue({ id: 1 });
Show answer
import { vi } from "vitest";
const save = vi.fn().mockResolvedValue({ id: 1 });Q4. Write a test.each table for a function grade(score) that returns “A” (90+), “B” (75–89) and “C” (below 75), covering the boundaries.
Show answer
test.each([
[100, "A"], [90, "A"], [89, "B"], [75, "B"], [74, "C"], [0, "C"],
])("grade(%i) is %s", (score, expected) => {
expect(grade(score)).toBe(expected);
});Q5. A test checks expect(sendEmail).toHaveBeenCalledTimes(1) and passes alone but fails when run after another test. What is the likely cause and fix?
Show answer
The mock’s call count carries over from the previous test. Clear mocks between tests with afterEach(() => jest.clearAllMocks()) or the clearMocks: true config option (Vitest: vi.clearAllMocks() / clearMocks).
Q6. Why does expect({ a: 1 }).toBe({ a: 1 }) fail, and what should you use?
Show answer
toBe uses Object.is, so two different objects are never equal even with identical content. Use toEqual (content) or toStrictEqual (content and types).
🧠 MCQ Quiz: Jest and Vitest
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which matcher compares objects by content?Answer: toEqual. toBe compares references for objects.
- How do you assert that a function throws in Jest?Answer: expect(() => fn()).toThrow(). Wrap the call in a function.
- How do you test that a promise resolves to 5?Answer: await expect(p).resolves.toBe(5). Or: expect(await p).toBe(5).
- What is the Vitest equivalent of jest.fn()?Answer: vi.fn(). vi.spyOn, vi.mock and vi.useFakeTimers follow the same pattern.
- What does jest.spyOn(obj, “m”) do?Answer: Watches an existing method and lets you replace its behaviour. Restore it with mockRestore().
- What does jest.mock(“./api”) do?Answer: Replaces the module’s exports with mock functions. Then configure return values per test.
- Which matcher checks a mock was called with specific arguments?Answer: toHaveBeenCalledWith. toHaveBeenCalledTimes checks the count.
- How do you make a 5-second setTimeout run instantly in Jest?Answer: jest.useFakeTimers() then jest.advanceTimersByTime(5000). Restore with jest.useRealTimers().
- Which command updates Jest snapshots?Answer: npx jest -u. Review the diff before committing.
- What is a main advantage of Vitest over Jest?Answer: Native ES modules and TypeScript with very fast runs. It reuses Vite’s transform pipeline.
💼 Interview Questions and Answers
Q1. What is the difference between toBe, toEqual and toStrictEqual?
toBe uses Object.is: right for primitives, but two objects are equal only if they are the same reference. toEqual recursively compares content and ignores properties that are undefined. toStrictEqual also checks undefined properties, sparse arrays and class types, so { a: 1, b: undefined } is not strictly equal to { a: 1 }.
Q2. How do you mock an API call in a unit test?
Isolate the call in a module or function, then replace it: jest.mock("./api") (or vi.mock) and set mockResolvedValue per test, or inject the client as a parameter and pass a jest.fn(). Assert both the result of your code and how the mock was called. For HTTP-level mocking, tools such as MSW (Mock Service Worker) intercept fetch requests.
Q3. Jest vs Vitest vs node:test: which would you choose?
For an existing Jest codebase or React projects with established tooling, keep Jest. For new projects, especially with Vite, ES modules or TypeScript, Vitest is faster and needs less configuration while keeping the same API. For small libraries, scripts and Node.js tools, node:test avoids any dependency. For end-to-end browser tests, none of them: use Playwright.
Q4. What are the risks of snapshot testing?
Large snapshots are hard to review, so people update them without reading (-u) and bless bugs. They fail on irrelevant changes such as timestamps or ordering, creating noise. Keep snapshots small and focused, prefer explicit assertions for the important values, mask dynamic data, and review snapshot diffs in pull requests.
❓ Frequently Asked Questions
🤔 Can Jest run ES modules?
Yes, with configuration: either transform with Babel, or run Node.js with --experimental-vm-modules and Jest’s ESM support. That friction is one reason many ESM projects choose Vitest.
🤔 How do I test React or Vue components?
Use Testing Library (@testing-library/react or /vue) with Jest or Vitest and a DOM environment (jsdom or happy-dom), or Playwright component testing to render components in a real browser.
🤔 What is the difference between clearAllMocks, resetAllMocks and restoreAllMocks?
clear resets recorded calls; reset also removes configured return values and implementations; restore also puts back the original methods replaced by spyOn.
🤔 Do Playwright tests use Jest?
No. Playwright has its own runner, @playwright/test, with a Jest-like expect plus web-first matchers, fixtures and browser management. The next lesson shows how your JavaScript knowledge maps onto it.
🏁 Summary
- Jest and Vitest share the same describe/test/expect API; Vitest is ESM-native and faster.
- Core matchers: toBe, toEqual, toStrictEqual, toContain, toMatch, toThrow, resolves/rejects; test.each for tables.
- jest.fn / vi.fn, spyOn and module mocks isolate dependencies; assert calls with toHaveBeenCalledWith.
- Fake timers make time-based code instant; clear mocks between tests.
- Snapshots and coverage help reviews but do not replace meaningful assertions; mock only slow or external dependencies.
Next, continue with Lesson 71: From JavaScript to Playwright.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in