Vitest: Lightning Fast Unit Tests

Vitest: Lightning Fast Unit Tests in JavaScript: Vitest is a modern testing framework designed for Vite.

Concept Explanation

Vitest is a modern testing framework designed for Vite. It is incredibly fast and uses the same syntax as the famous "Jest" framework, so your skills are transferable.


Syntax or Core Structure

A Simple Test

// math.js
export const add = (a, b) => a + b;

// math.test.js
import { expect, test } from 'vitest';
import { add } from './math';

test('adds 1 + 2 to equal 3', () => {
  expect(add(1, 2)).toBe(3);
});

Technical Concept: Assertions

An Assertion is a claim. expect(result).toBe(10) is you claiming that the result will be 10. If it isn't, the test fails and tells you exactly what happened.


Common Matchers

expect(sum).toBe(5);             // strict equality (numbers, strings)
expect(user).toEqual({ id: 1 }); // deep equality (objects, arrays)
expect(list).toContain("apple");  // array/string includes
expect(isReady).toBeTruthy();     // truthy check
expect(() => boom()).toThrow();   // expects a thrown error

Group related tests and share setup with describe and beforeEach:

describe("cart", () => {
  let cart;
  beforeEach(() => { cart = []; }); // fresh state per test
  test("starts empty", () => expect(cart.length).toBe(0));
});

Common Mistakes

  • toBe on Objects: toBe checks reference identity — two identical objects aren't toBe equal. Use toEqual.
  • No Isolation: Tests that share state fail randomly depending on order. Reset in beforeEach.
  • One Giant Test: A test asserting ten things gives a vague failure. Prefer many small, focused tests.

Best Practices

  • Arrange-Act-Assert: Structure each test in three clear steps.
  • Test Behavior: Assert outputs, not internal calls, so refactors don't break tests.
  • Watch Mode: Run vitest in watch mode so tests re-run the instant you save.

Practice Exercises

  1. The Calculator: Write a subtract function and a corresponding test in Vitest.
  2. The Object Matcher: Use .toEqual() to test if two objects have the same properties (Hint: .toBe() won't work for objects!).
  3. The Async Test: Write a test for a function that returns a Promise using async/await inside the test.