Vitest & Jest Testing Cheat Sheet
Quick reference guide for Vitest & Jest: Test suite syntax, assertion methods, mocks, spies, and async testing.
Testing
vitest
jest
testing
Vitest and Jest are blazing fast unit test frameworks with built-in mocking, assertion libraries, and code coverage support for JavaScript and TypeScript.
Common Expect Matchers Reference
Table
| Matcher | Example Usage | Description |
|---|---|---|
toBe(val) | expect(a).toBe(5) | Strict equality (===) |
toEqual(obj) | expect(user).toEqual({ id: 1 }) | Deep object structural equality |
toBeTruthy() / toBeFalsy() | expect(val).toBeTruthy() | Truthy / Falsy boolean check |
toContain(item) | expect(arr).toContain('admin') | Array or String inclusion check |
toHaveProperty(key) | expect(obj).toHaveProperty('role') | Check object key presence |
toThrow(msg) | expect(fn).toThrow(/invalid/) | Test function exception throw |
toHaveBeenCalledWith() | expect(spy).toHaveBeenCalledWith(1) | Check mock function arguments |
Test Suite & Mocking Example
typescript
import { describe, it, expect, vi, beforeEach } from "vitest";
// Note: For Jest, replace `vi` with `jest`
import { UserService } from "./user.service";
describe("UserService", () => {
let service: UserService;
const mockApiCall = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
service = new UserService(mockApiCall);
});
it("fetches user by ID successfully", async () => {
mockApiCall.mockResolvedValueOnce({ id: 1, name: "Alice" });
const user = await service.getUser(1);
expect(mockApiCall).toHaveBeenCalledTimes(1);
expect(mockApiCall).toHaveBeenCalledWith(1);
expect(user.name).toBe("Alice");
});
it("handles async network error gracefully", async () => {
mockApiCall.mockRejectedValueOnce(new Error("Network Error"));
await expect(service.getUser(99)).rejects.toThrow("Network Error");
});
});
Mocking Timers & Modules
typescript
// Mock timer ticks
vi.useFakeTimers();
setTimeout(() => console.log("done"), 1000);
vi.advanceTimersByTime(1000);
vi.useRealTimers();
// Mock entire ES Module
vi.mock("./api-client", () => ({
fetchData: vi.fn().mockResolvedValue(["data1", "data2"])
}));
Common Pitfalls & Tips
[!WARNING] Testing thrown errors requires wrapping the function execution inside an anonymous function:
expect(() => fn()).toThrow().
[!TIP] Use
beforeEach(() => vi.clearAllMocks())to reset call history between individual test specs to prevent mock state pollution across tests.