| name | jest-vitest |
| description | JavaScript/TypeScript testing with Jest and Vitest. Use when user asks to "write JS tests", "add unit tests", "test React component", "mock a module", "snapshot testing", "test async code", "set up Jest", "migrate to Vitest", or any JS/TS testing tasks. |
Jest & Vitest
JavaScript/TypeScript testing with Jest and Vitest.
Running Tests
npx jest
npx jest --watch
npx jest --coverage
npx jest path/to/test.ts
npx jest -t "test name pattern"
npx vitest
npx vitest run
npx vitest --coverage
npx vitest path/to/test.ts
Test Structure
describe("Calculator", () => {
let calc: Calculator;
beforeEach(() => {
calc = new Calculator();
});
afterEach(() => {
calc.reset();
});
it("should add two numbers", () => {
expect(calc.add(2, 3)).toBe(5);
});
it("should throw on division by zero", () => {
expect(() => calc.divide(1, 0)).toThrow("Division by zero");
});
describe("negative numbers", () => {
it("should handle negative addition", () => {
expect(calc.add(-1, -2)).toBe(-3);
});
});
});
Common Matchers
expect(value).toBe(exact);
expect(value).toEqual(deepEqual);
expect(value).toStrictEqual(strict);
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeUndefined();
expect(value).toBeDefined();
expect(value).toBeGreaterThan(3);
expect(value).toBeLessThanOrEqual(10);
expect(value).toBeCloseTo(0.3, 5);
expect(str).toMatch(/regex/);
expect(str).toContain("substring");
expect(arr).toContain(item);
expect(arr).toHaveLength(3);
expect(obj).toHaveProperty("key", );
(obj).({ : });
( ()).();
( ()).();
( ()).();
Mocking
const mockFn = jest.fn();
const mockFn = vi.fn();
mockFn.mockReturnValue(42);
mockFn.mockReturnValueOnce(1);
mockFn.mockResolvedValue({ data: [] });
mockFn.mockImplementation((x) => x * 2);
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledTimes(2);
expect(mockFn).toHaveBeenCalledWith("arg1", "arg2");
jest.mock("./database");
vi.mock("./database");
jest.mock("./api", () => ({
fetchUser: jest.fn().mockResolvedValue({ name: "Alice" }),
}));
vi.mock("./api", () => ({
fetchUser: vi.fn().({ : }),
}));
spy = jest.(, );
spy = vi.(, );
jest.();
vi.();
jest.();
vi.();
Async Testing
it("fetches users", async () => {
const users = await fetchUsers();
expect(users).toHaveLength(3);
});
it("resolves with data", async () => {
await expect(fetchData()).resolves.toEqual({ ok: true });
});
it("rejects with error", async () => {
await expect(fetchBad()).rejects.toThrow("Network error");
});
Snapshot Testing
it("renders correctly", () => {
const tree = render(<Button label="Click" />);
expect(tree).toMatchSnapshot();
});
it("serializes", () => {
expect(serialize(data)).toMatchInlineSnapshot(`"expected output"`);
});
React Testing (Testing Library)
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
it("renders and interacts", async () => {
render(<LoginForm onSubmit={mockSubmit} />);
const input = screen.getByRole("textbox", { name: /email/i });
const button = screen.getByRole("button", { name: /submit/i });
fireEvent.change(input, { target: { value: "alice@test.com" } });
fireEvent.click(button);
await waitFor(() => {
expect(mockSubmit).toHaveBeenCalledWith("alice@test.com");
});
expect(screen.getByText("Success")).toBeInTheDocument();
});
import userEvent from "@testing-library/user-event";
it("types and submits", async () => {
const user = userEvent.setup();
();
user.(screen.(), );
user.(screen.());
});
Coverage
npx jest --coverage --coverageThreshold='{"global":{"branches":80,"functions":80,"lines":80}}'
Configuration
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: true,
environment: "jsdom",
setupFiles: ["./tests/setup.ts"],
coverage: {
provider: "v8",
reporter: ["text", "html"],
exclude: ["node_modules/", "tests/"],
},
},
});
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom",
setupFilesAfterSetup: ["./tests/setup.ts"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
coverageThreshold: {
global: { branches: 80, functions: 80, lines: 80, statements: 80 },
},
};
Reference
For advanced patterns, React testing recipes, and migration guides: references/patterns.md