読み物Testing

Level: Basic

Writing Your First Automated Unit Tests with TypeScript and Vitest

Set up Vitest, write testable code and its tests, watch a real test fail on a boundary bug, read the failure line by line, fix it, and see it pass.

Edeeson Opina7 min read

A Basic lesson card: lesson 4 of the Software Testing & Quality Engineering series, Writing Your First Automated Unit Tests with TypeScript and Vitest, with the Miso fox holding a camera.

What you’ll learn

  • Set up Vitest in a TypeScript project
  • Write testable functions and Arrange, Act, Assert tests
  • Read a failing test's output and locate the defect
  • Use the most common assertions correctly
On this page
  1. Before you start
  2. Setting up the project
  3. Writing testable code
  4. Writing the tests
  5. Watching a test fail
  6. Reading the failure
  7. Fixing the code
  8. Assertions you'll use most
  9. Running tests while you work
  10. Common mistakes and troubleshooting
  11. Practical exercise: test and fix a function
  12. Key takeaways
  13. References
  14. What's next

This lesson builds your first automated tests from an empty folder. You'll set up a TypeScript project with Vitest, write a small function and its tests, watch a test fail because of a real defect, read the failure output line by line, fix the code, and see the suite pass. Along the way you'll learn what makes code easy to test and the handful of assertions you'll use most. The output shown is real, from Vitest 5.

Before you start

You should be comfortable with test design from How to Write Effective Test Cases: Test Design Techniques Explained, and have Node.js installed (Vitest 5 needs version 22.12 or newer) and a code editor. Basic TypeScript or JavaScript is enough.

Setting up the project

Vitest is a test runner for JavaScript and TypeScript. It runs TypeScript files directly, without a separate build step, and its API will look familiar if you've seen Jest.

Shell
mkdir shop && cd shop
npm init -y
npm install --save-dev vitest typescript

Add a script to package.json and set the module type:

package.jsonJSON
{
  "name": "shop",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "vitest run",
    "test:watch": "vitest"
  },
  "devDependencies": {
    "typescript": "^7.0.0",
    "vitest": "^5.0.0"
  }
}

vitest run runs every test once and exits, which is what CI needs. Plain vitest starts watch mode, re-running affected tests whenever you save a file.

Vitest finds test files by name: anything ending in .test.ts or .spec.ts (and the JavaScript equivalents). Keep each test file next to the code it tests.

Writing testable code

Here's the function to test, from the shop's requirement: "Orders of 5,000 cents or more get 10% off."

src/cart.tsTypeScript
export type Item = { name: string; priceCents: number; quantity: number };

/** Total in cents. Orders of 5,000 cents or more get 10% off. */
export function cartTotal(items: Item[]): number {
  const subtotal = items.reduce((sum, item) => sum + item.priceCents * item.quantity, 0);
  return subtotal > 5000 ? Math.round(subtotal * 0.9) : subtotal;
}

Notice what makes this easy to test:

  • It's a pure function: the same input always gives the same output, and it doesn't read the clock, call the network, or change anything outside itself.
  • It takes its inputs as parameters instead of reading global state.
  • It uses integer cents, not floating-point currency, so 0.1 + 0.2 problems can't creep in.

When code mixes calculation with side effects (reading a database, sending email), testing gets harder. A good habit is to keep the decision-making in pure functions and the side effects at the edges. Lesson 6 shows how to test code that does have side effects.

Writing the tests

Create src/cart.test.ts. Each test follows the same shape, often called Arrange, Act, Assert: set up the input, call the code, check the result.

src/cart.test.tsTypeScript
import { describe, expect, it } from "vitest";
import { cartTotal } from "./cart";

describe("cartTotal", () => {
  it("adds up price times quantity", () => {
    expect(cartTotal([{ name: "Miso", priceCents: 450, quantity: 2 }])).toBe(900);
  });

  it("is zero for an empty cart", () => {
    expect(cartTotal([])).toBe(0);
  });

  it("gives 10% off at exactly 5,000 cents", () => {
    expect(cartTotal([{ name: "Gift box", priceCents: 5000, quantity: 1 }])).toBe(4500);
  });
});
  • describe groups related tests under a name.
  • it (or its alias test) defines one test with a name that reads as a sentence.
  • expect(actual).toBe(expected) is the assertion.

The third test is the boundary value from lesson 3: exactly 5,000 cents, the edge of the discount rule.

Watching a test fail

Run the suite:

Shell
npm test
Text
 ❯ src/cart.test.ts (3 tests | 1 failed) 7ms
   ❯ cartTotal (3)
     × gives 10% off at exactly 5,000 cents 4ms

⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/cart.test.ts > cartTotal > gives 10% off at exactly 5,000 cents
AssertionError: expected 5000 to be 4500 // Object.is equality

- Expected
+ Received

- 4500
+ 5000

 ❯ src/cart.test.ts:14:78
     12|
     13|   it("gives 10% off at exactly 5,000 cents", () => {
     14|     expect(cartTotal([{ name: "Gift box", priceCents: 5000, quantity: …
       |                                                                              ^

 Test Files  1 failed (1)
      Tests  1 failed | 2 passed (3)

Reading the failure

Read it from the top, the way you'd read an error message from a colleague:

  1. Which test: cartTotal > gives 10% off at exactly 5,000 cents. A descriptive test name already tells you which requirement is broken.
  2. What was expected and what happened: expected 5000 to be 4500. The function returned 5,000, the full price; the test expected 4,500, the discounted price. The - Expected / + Received block shows the same thing as a diff, which is especially useful for objects and arrays.
  3. Where: line 14 of the test file, with the code shown.
  4. The summary: one failed, two passed.

The other two tests passing tells you something too: totals in general work; only the discount at the boundary is wrong. That narrows the search to one condition in cartTotal.

Fixing the code

The requirement says "5,000 cents or more," but the code says subtotal > 5000, more than 5,000. That's the off-by-one boundary defect boundary value analysis is designed to catch. The fix is one character:

src/cart.tsTypeScript
return subtotal >= 5000 ? Math.round(subtotal * 0.9) : subtotal;

Run the tests again:

Text
 ✓ src/cart.test.ts (3 tests) 2ms

 Test Files  1 passed (1)
      Tests  3 passed (3)

Two things to notice. First, the test failed before the fix and passes after it; that's how you know the test actually checks the behavior. A test you've never seen fail might not test anything. Second, the failing test now stays in the suite as a regression test: if anyone changes >= back to >, it fails again.

Assertions you'll use most

TypeScript
expect(value).toBe(42);                       // same value (Object.is); use for primitives
expect(order).toEqual({ id: 1, items: [] });  // deep equality; use for objects and arrays
expect(list).toHaveLength(3);
expect(list).toContain("miso");
expect(text).toMatch(/discount/i);
expect(value).toBeNull();
expect(() => parsePrice("abc")).toThrow("Invalid price");
await expect(loadOrder("missing")).rejects.toThrow("Not found");

A common surprise: expect({ a: 1 }).toBe({ a: 1 }) fails, because two separate objects aren't the same object. Use toEqual for objects.

For asynchronous code, make the test function async and await the result. A test that forgets to await a promise can pass even when the promise rejects.

Running tests while you work

  • npx vitest (watch mode) re-runs related tests on every save; it's the fastest feedback loop.
  • npx vitest run src/cart.test.ts runs one file.
  • npx vitest run -t "exactly 5,000" runs tests whose names match.
  • it.only runs just one test while you focus on it, and it.skip skips one. Remove both before committing: a forgotten .only silently skips the rest of the suite. Vitest can refuse .only in CI with the allowOnly: false setting (its default when the CI environment variable is set).

Common mistakes and troubleshooting

  • Never seeing the test fail. Break the code on purpose once to confirm the test catches it.
  • Testing implementation instead of behavior. Assert on results, not on how the function computes them.
  • toBe on objects. Use toEqual.
  • Missing await. Async tests must await what they check.
  • Floating-point money. Use integer cents, or a decimal library, and avoid comparing floats with toBe; use toBeCloseTo when floats are unavoidable.
  • "No test files found." Check the file name ends in .test.ts and that you're running from the project root.
  • Leftover .only. Search for it before committing.

Practical exercise: test and fix a function

  1. Set up the project above and add cartTotal with the > defect.
  2. Write the three tests, run them, and read the failure as shown.
  3. Fix the code and confirm all tests pass.
  4. Add parameterized boundary tests for 4,999, 5,000, and 5,001 cents (lesson 3).
  5. Add a function parsePrice(text: string): number that converts "12.50" to 1250 and throws for invalid input. Write tests first for valid, invalid, and boundary inputs, then implement it.
  6. Break one line of parsePrice on purpose and check that at least one test fails.

Key takeaways

  • Vitest runs TypeScript tests directly; vitest run for CI, vitest for watch mode.
  • Pure functions with parameters are the easiest code to test.
  • Structure tests as Arrange, Act, Assert, with names that read as requirements.
  • Read failures top to bottom: which test, expected versus received, where.
  • A test that has never failed might not test anything; a fixed bug's test stays as a regression test.

References

What's next

Automated tests check what you thought of. Manual Testing, Exploratory Testing, Bug Reports, and Regression Testing covers finding what you didn't think of, and reporting it so it gets fixed.

See every lesson in Software Testing & Quality Engineering: From Fundamentals to Production-Ready Software