Vitest 03 🧪 Writing Your First Test — test, expect, and .test.js Files
A test file in Vitest is a JavaScript or TypeScript module that imports test and expect from vitest, defines one or more test cases, and asserts on the results. The structure is deliberately close to Jest’s: test (or its alias it) declares a case, expect wraps a value and returns an object of matchers, and a failed matcher throws an error that Vitest reports with the file, line, and diff . The difference from a plain script is not syntax; it is that Vitest discovers the file by name, runs it in an isolated environment, and treats a thrown error as a test failure.
This chapter covers the anatomy of a test file, the test/it and expect APIs, and the file-naming convention that determines what Vitest runs. The sections that follow walk through the test case structure, the matcher API, and the discovery rules that decide which files are tests.
Key point: A Vitest test is a file matching the include pattern (by default *.test.* or *.spec.*) that imports test and expect from vitest; a test fails if it throws, and an assertion failure is a thrown error from a matcher.
a. The test case structure
test and it are the same function with two names. The first argument is the test name (a string), the second is the test body (a function). The body runs synchronously unless it returns a Promise, in which case Vitest waits for the Promise to settle .
import { test, expect } from "vitest";
import { add } from "./math";
test("adds two numbers", () => {
expect(add(1, 2)).toBe(3);
});
// `it` is an alias for `test`
import { it } from "vitest";
it("also adds two numbers", () => {
expect(add(2, 3)).toBe(5);
});
Tests are grouped with describe, which takes a name and a callback. The callback contains the tests, and nested describe blocks create nested groups. The grouping is for organization and for hooks (beforeEach, afterEach) that apply to the tests inside the block .
import { describe, test, expect } from "vitest";
describe("math", () => {
describe("add", () => {
test("returns the sum of two positives", () => {
expect(add(1, 2)).toBe(3);
});
test("handles negatives", () => {
expect(add(-1, -2)).toBe(-3);
});
});
});
A test that throws fails. The throw can be an assertion failure from expect, an explicit throw, or an unhandled rejection from an async body. Vitest reports the error with the test name, the file, and the line where the failure occurred. A test that does not throw passes, even if it contains no assertions; Vitest does not enforce that every test asserts something.
b. The expect API and the matcher set
expect(value) returns an object of matchers. The matcher is called with the expected value, and it either returns normally (pass) or throws an AssertionError (fail). The matchers are named for the assertion they make: .toBe() for Object.is equality, .toEqual() for deep equality, .toBeTruthy() for truthiness, .toThrow() for thrown errors, and so on .
import { expect } from "vitest";
// Primitives: Object.is equality
expect(2 + 2).toBe(4);
expect("hello").toBe("hello");
// Objects and arrays: deep equality
expect({ a: 1 }).toEqual({ a: 1 });
expect([1, 2, 3]).toEqual([1, 2, 3]);
// Truthiness
expect("").toBeFalsy();
expect(1).toBeTruthy();
expect(null).toBeNull();
expect(undefined).toBeUndefined();
// Numbers
expect(10).toBeGreaterThan(5);
expect(0.1 + 0.2).toBeCloseTo(0.3);
// Strings
expect("vitest").toMatch(/vit/);
// Errors
expect(() => { throw new Error("boom"); }).toThrow("boom");
// Asymmetric matchers inside toEqual
expect({ id: 1, name: "Ana" }).toEqual({
id: expect.any(Number),
name: expect.stringContaining("An"),
});
The .not property inverts any matcher: expect(1).not.toBe(2). The asymmetric matchers—expect.any(), expect.anything(), expect.stringContaining(), expect.objectContaining(), expect.arrayContaining()—are used inside toEqual to assert on parts of a value without specifying the whole thing .
The @testing-library/jest-dom matchers (.toBeInTheDocument(), .toHaveTextContent(), .toBeVisible()) are not part of Vitest; they are installed separately and registered in a setup file. Without the setup, the matcher is undefined and the test throws a TypeError rather than failing an assertion.
c. File discovery and naming
Vitest does not scan every file. It matches the include pattern, which defaults to **/*.{test,spec}.?(c|m)[jt]s?(x) . A file named math.test.ts, math.spec.ts, math.test.js, or math.test.tsx is a test; a file named math.ts is not. The exclude pattern defaults to **/node_modules/**, **/dist/**, and the other build directories, so tests inside dependencies are not run .
// vite.config.ts
export default defineConfig({
test: {
include: ["src/**/*.test.ts", "src/**/*.test.tsx"],
exclude: ["node_modules", "dist"],
},
});
The convention is to place the test next to the source file (math.ts and math.test.ts in the same directory) or in a __tests__ directory. Both work; the co-located pattern is the more common one in Vite projects because it keeps the test and the implementation in the same visual context .
A test file with no tests fails with “No test suite found in file” when Vitest tries to collect it. A test file that imports a module with a side effect runs that side effect at collection time, before any test executes; this is why mocks that need to be hoisted use vi.hoisted() .
Complete Example Session
// ============================================
// PART 1: THE MODULE UNDER TEST
// ============================================
// src/math.ts
export function add(a: number, b: number): number {
return a + b;
}
export function divide(a: number, b: number): number {
if (b === 0) throw new Error("Division by zero");
return a / b;
}
// ============================================
// PART 2: THE TEST FILE
// ============================================
// src/math.test.ts
import { describe, test, it, expect } from "vitest";
import { add, divide } from "./math";
describe("add", () => {
test("adds two positives", () => {
expect(add(1, 2)).toBe(3);
});
it("handles negatives", () => {
expect(add(-1, -2)).toBe(-3);
});
});
describe("divide", () => {
test("divides two numbers", () => {
expect(divide(10, 2)).toBe(5);
});
test("throws on division by zero", () => {
expect(() => divide(1, 0)).toThrow("Division by zero");
});
});
// ============================================
// PART 3: THE ASYMMETRIC MATCHERS
// ============================================
test("object with any id", () => {
const user = { id: 42, name: "Ana" };
expect(user).toEqual({
id: expect.any(Number),
name: expect.stringContaining("An"),
});
});
The parts covered the module under test, the test file with describe/test/it, the error assertion, and the asymmetric matchers.
Quick Reference
Test Functions
| Function | Alias | Purpose |
|---|---|---|
test(name, fn) | it | Declare a test case |
describe(name, fn) | — | Group tests |
test.skip | it.skip | Skip a test |
test.only | it.only | Run only this test |
test.todo | — | Mark a test as todo |
Common Matchers
| Matcher | Asserts |
|---|---|
.toBe(v) | Object.is equality |
.toEqual(v) | Deep equality |
.toBeTruthy() / .toBeFalsy() | Truthiness |
.toBeNull() / .toBeUndefined() | Null/undefined |
.toMatch(re) | String matches regex |
.toThrow(msg) | Function throws |
.toBeGreaterThan(n) | Numeric comparison |
.toBeCloseTo(n) | Floating-point proximity |
.not | Inverts any matcher |
File Discovery
| Pattern | Matches |
|---|---|
*.test.ts | Yes |
*.spec.ts | Yes |
*.test.tsx | Yes |
*.ts | No |
Best Practices
✅ Do This:
// Use test or it consistently
test("adds", () => { ... }); // ✅
// Use toEqual for objects
expect({ a: 1 }).toEqual({ a: 1 }); // ✅
// Use asymmetric matchers for partial objects
expect(user).toEqual({ id: expect.any(Number) }); // ✅
// Test the throw
expect(() => divide(1, 0)).toThrow("Division by zero"); // ✅
❌ Don’t Do This:
// Use toBe for objects
expect({ a: 1 }).toBe({ a: 1 }); // always fails // ❌
// Forget the arrow wrapper for toThrow
expect(divide(1, 0)).toThrow(); // throws before expect // ❌
// Assert in a test that does not import expect
test("x", () => { expect(1).toBe(1); }); // ReferenceError // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
toBe fails on objects | Reference comparison | Use toEqual |
toThrow does not catch | Called the function instead of passing it | Wrap in () => fn() |
| No test suite found | Empty file or no test call | Add at least one test |
| jest-dom matcher undefined | Not registered in setup | Add setup file and import |
| Globals undefined | globals: false default | Import from vitest |
Real-World Examples
1. Basic test
test("adds", () => { expect(add(1, 2)).toBe(3); });
2. Grouped tests
describe("math", () => { test("adds", () => { ... }); });
3. Deep equality
expect({ a: 1 }).toEqual({ a: 1 });
4. Throw assertion
expect(() => fn()).toThrow("message");
5. Asymmetric matcher
expect(user).toEqual({ id: expect.any(Number) });
6. Skip
test.skip("not ready", () => { ... });
7. Only
test.only("focus", () => { ... });
8. Todo
test.todo("implement later");
9. Regex match
expect("vitest").toMatch(/vit/);
10. Floating point
expect(0.1 + 0.2).toBeCloseTo(0.3);
Visual
Test File Anatomy
┌─────────────────────────────────────────────────────────┐
│ math.test.ts │
│ ┌──────────────────────────────────────────┐ │
│ │ import { test, expect } from "vitest" │ │
│ │ │ │
│ │ describe("math", () => { │ │
│ │ test("adds", () => { │ │
│ │ expect(add(1, 2)).toBe(3) │ │
│ │ }) │ │
│ │ }) │ │
│ └──────────────────────────────────────────┘ │
│ │
│ Discovered by *.test.ts pattern │
│ Runs in isolation, throws on failure │
└─────────────────────────────────────────────────────────┘
Matcher Selection
┌─────────────────────────────────────────────────────────┐
│ PRIMITIVE OBJECT │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ toBe │ │ toEqual │ │
│ │ Object.is │ │ deep equality │ │
│ └──────────────────┘ └──────────────────┘ │
│ │
│ ERROR PARTIAL │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ toThrow(() => fn)│ │ expect.any() │ │
│ │ │ │ expect.objectContaining() │ │
│ └──────────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────┘
Discovery
┌─────────────────────────────────────────────────────────┐
│ INCLUDED EXCLUDED │
│ math.test.ts math.ts │
│ math.spec.ts node_modules/ │
│ math.test.tsx dist/ │
│ __tests__/math.ts coverage/ │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Test function | test(name, fn) / it(name, fn) |
| Grouping | describe(name, fn) |
| Assertion | expect(value).matcher(expected) |
| Primitive equality | .toBe() (Object.is) |
| Deep equality | .toEqual() |
| Error assertion | .toThrow() with wrapper |
| Inversion | .not |
| File pattern | *.test.* / *.spec.* |
Key takeaways:
- A test is a function that throws on failure.
testdeclares the case,expectthrows theAssertionError, and Vitest reports the error with the file and line. A test that does not throw passes . toBeis for primitives;toEqualis for objects.toBeusesObject.is, so two structurally equal objects fail it.toEqualdoes deep equality and is the correct matcher for objects and arrays .toThrowneeds the function, not the call.expect(fn()).toThrow()callsfnbeforeexpectcan catch the throw. The wrapperexpect(() => fn()).toThrow()is the correct form .- The file name determines discovery. Vitest runs
*.test.*and*.spec.*by default. A file with tests but no matching name is never collected, and a matching file with notestcall fails with “No test suite found” . - Asymmetric matchers assert on parts of a value.
expect.any(Number),expect.stringContaining(), andexpect.objectContaining()let atoEqualassert on some fields without specifying every field .
Remember: A Vitest test is a small program that either returns normally or throws. The test and expect functions are the vocabulary; the file name is the discovery mechanism. Use toBe for primitives, toEqual for structures, and toThrow with the arrow wrapper for errors. Place the test next to the source with a .test.ts suffix, import from vitest, and let the thrown assertion be the failure signal.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!