🧪 Tools

Testing JavaScript with Vitest — Your First Test Suite

📅 Jul 5, 2026 ⏱ 3 min read

"Do you write tests?" is a real interview question. After this post, your honest answer is yes.

Setup (Vitest — Jest's modern twin)

npm i -D vitest
// package.json: "test": "vitest"

First tests

// gpa.js
export function calculateGpa(marks) {
  if (!marks.length) return 0;
  const points = marks.map((m) => m >= 90 ? 10 : m >= 80 ? 9 : m >= 70 ? 8 : 0);
  return +(points.reduce((a, b) => a + b) / marks.length).toFixed(2);
}

// gpa.test.js
import { describe, it, expect } from "vitest";
import { calculateGpa } from "./gpa.js";

describe("calculateGpa", () => {
  it("computes a simple average", () => {
    expect(calculateGpa([95, 85])).toBe(9.5);
  });
  it("handles empty input", () => {
    expect(calculateGpa([])).toBe(0);        // the edge case!
  });
  it("rounds to 2 decimals", () => {
    expect(calculateGpa([95, 85, 75])).toBe(9);
  });
});

npx vitest — tests re-run on every save. Red → fix → green is addictive.

What to test (and skip)

The deeper win: code that's hard to test is badly structured — testing pressure produces the small pure functions from the clean code guide. One tested project on GitHub quietly outranks ten untested ones.

← All Articles