agentleFS
G1JoshiG1Joshi/Agent-Skills/skills/testing/jest/SKILL.md

jest

Skill15 starsChanged 43 days agoMITView on GitHub

Expert Jest testing assistance covering unit testing, snapshot testing, mocking, and coverage reports. Use when writing tests for JavaScript/TypeScript, React, Node.js, or Next.js applications.

4 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

5 rules. 0 are common, 1 is distinctive, and 4 are very specific to this project.

  • 0

    Common

    Most of the 4 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use jest.mock and jest.spyOn:

    line 94
  2. Very specific:

    Use @swc/jest for Fast TypeScript Compilation: Replace slow ts-jest with SWC compiler to dramatically accelerate execution.

    line 118
  3. Very specific:

    Use test.each for Table-Driven Test Cases: Consolidate repetitive test scenarios into parameterized tables.

    line 119
  4. Distinctive:

    Keep Snapshots Small: Avoid snapshotting massive DOM trees.

    line 120
  5. Very specific:

    Leave hanging asynchronous promises: Always return promises or await async calls to avoid unhandled rejections.

    line 126

“Common” is measured: kept by at least 6 in 10 of the 4 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Jest

Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue, and more.

When to Use

  • JavaScript & TypeScript Unit Testing: Standard, battery-included test runner for React, Node.js, and legacy frontend projects.
  • Snapshot Testing: Freezing and asserting on large rendered component output, GraphQL responses, or JSON configurations.
  • Comprehensive Mocking Engine: Spying on, mocking, and stubbing functions, timers, and entire modules with jest.mock().
  • Code Coverage Reporting: Generating built-in Istanbul code coverage metrics without external plugins.

Quick Start

// sum.js
function sum(a, b) {
  return a + b;
}
module.exports = sum;

// sum.test.js
const sum = require("./sum");

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

Core Concepts

Module Mocking & Function Spies (jest.fn(), jest.mock())

Replaces dependencies with mock implementations:

// service.test.ts
import { sendWelcomeEmail } from "./mailer";
import { registerUser } from "./user.service";

jest.mock("./mailer", () => ({
  sendWelcomeEmail: jest.fn().mockResolvedValue(true),
}));

test("sends welcome email upon registration", async () => {
  const result = await registerUser("test@example.com");
  expect(result.success).toBe(true);
  expect(sendWelcomeEmail).toHaveBeenCalledWith("test@example.com");
  expect(sendWelcomeEmail).toHaveBeenCalledTimes(1);
});

Fake Timers for Asynchronous Delays

Fast-forwards debounce timers, intervals, and timeouts instantaneously:

test("debounced search triggers after 300ms", () => {
  jest.useFakeTimers();
  const searchMock = jest.fn();

  triggerDebouncedSearch(searchMock, "query");
  expect(searchMock).not.toHaveBeenCalled();

  // Fast forward clock
  jest.advanceTimersByTime(300);
  expect(searchMock).toHaveBeenCalledWith("query");
  jest.useRealTimers();
});

Snapshot Assertions

Detects unintended regressions in complex structures:

test("matches expected invoice schema snapshot", () => {
  const invoice = generateInvoiceTemplate();
  expect(invoice).toMatchSnapshot();
});

Common Patterns

Mocking External Modules and Spying on Calls

Problem: Unit tests hitting third-party SDKs or database clients slow down test runs and produce side effects.

Solution: Use jest.mock and jest.spyOn:

import axios from "axios";
import { fetchUserData } from "./userService";

jest.mock("axios");
const mockedAxios = axios as jest.Mocked<typeof axios>;

test("fetches successfully data from an API", async () => {
  const data = { id: 1, name: "John" };
  mockedAxios.get.mockResolvedValueOnce({ data });

  const result = await fetchUserData(1);
  expect(result).toEqual(data);
  expect(mockedAxios.get).toHaveBeenCalledWith("/api/users/1");
});

Best Practices

Do:

  • Clear Mocks Between Tests: Enable clearMocks: true in jest.config.js to prevent call count contamination across tests.
  • Use @swc/jest for Fast TypeScript Compilation: Replace slow ts-jest with SWC compiler to dramatically accelerate execution.
  • Use test.each for Table-Driven Test Cases: Consolidate repetitive test scenarios into parameterized tables.
  • Keep Snapshots Small: Avoid snapshotting massive DOM trees; snapshot focused component states and data contracts.

Don't:

  • Blindly update snapshots (-u): Review snapshot diffs carefully before accepting changes to prevent approving bugs.
  • Mock what you don't own: Avoid mocking third-party libraries excessively; prefer integration tests with real adapters where possible.
  • Leave hanging asynchronous promises: Always return promises or await async calls to avoid unhandled rejections.

Troubleshooting

ErrorCauseSolution
Cannot use import statement outside a moduleJest attempting to execute ESM files without proper Babel/ts-jest transform.Configure ts-jest or set "transform": {} in jest.config.js.
A worker process has failed to exit gracefullyOpen handles, database connections, or active timers remaining.Run with --detectOpenHandles and close connections in afterAll.
Snapshot mismatch errorIntended UI or markup change failed snapshot assertion.Review diff and update snapshots with jest -u.

References

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.