JavaScript · Lesson 15 of 15
Testing JavaScript
Unit tests with Node's built-in runner or Jest, assertions and mocking.
- Advanced
- 13 min read
- 3 objectives
Before this lessonLesson 14: Iterators, Generators, Map and Set
What you will learn
- Write unit tests
- Run tests from npm
- Mock a dependency
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 3 hours
Progress is saved in this browser. No account needed.
Tip: pressing Next marks this lesson complete automatically.
Tests are code that checks your code. They catch regressions when you change things later and document how functions should behave.
The built-in Node test runner
// sum.js
export function sum(a, b) { return a + b; }
// sum.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
import { sum } from "./sum.js";
test("adds numbers", () => {
assert.equal(sum(2, 3), 5);
});
test("adds negatives", () => {
assert.equal(sum(-2, -3), -5);
});node --testJest / Vitest style
Most projects use Jest or Vitest. Their API is nearly identical: describe groups tests, test defines one, and expect checks a value.
import { describe, test, expect } from "vitest";
import { sum } from "./sum.js";
describe("sum", () => {
test("adds", () => {
expect(sum(1, 2)).toBe(3);
});
test("arrays compare by value with toEqual", () => {
expect([1, 2]).toEqual([1, 2]);
});
test("throws", () => {
expect(() => JSON.parse("{")).toThrow();
});
});Async tests and mocks
import { test, expect, vi } from "vitest";
test("loads a user", async () => {
const fetchUser = vi.fn().mockResolvedValue({ name: "Ada" }); // fake dependency
const user = await fetchUser(1);
expect(user.name).toBe("Ada");
expect(fetchUser).toHaveBeenCalledWith(1);
});Add it to npm
npm pkg set scripts.test="vitest run"
npm testFinished reading? Mark this lesson complete to track your progress.
