Jest

From G1Joshi/Agent-Skills · View interactive version

Jest is an AI agent skill from the GitHub repository G1Joshi/Agent-Skills. 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.

How to use this skill

Skill file

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

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:

Don't:

Troubleshooting

| Error | Cause | Solution |

| :----------------------------------------------- | :--------------------------------------------------------------------------- | :------------------------------------------------------------------ |

| Cannot use import statement outside a module | Jest 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 gracefully | Open handles, database connections, or active timers remaining. | Run with --detectOpenHandles and close connections in afterAll. |

| Snapshot mismatch error | Intended UI or markup change failed snapshot assertion. | Review diff and update snapshots with jest -u. |

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.