Prompts Jest Testing

Best ChatGPT Prompt for Generating Jest Unit Tests Fast

Best ChatGPT Prompt for Generating Jest Unit Tests

When to Use This Prompt

Use this when you need full Jest test coverage for a function or module without writing every case by hand. The prompt generates happy-path tests, edge cases, and mocked external calls (APIs, databases, timers) in one shot. Works with JavaScript and TypeScript.

The Prompt (Copy & Paste)

Paste the prompt, then replace [PASTE FUNCTION HERE] with your actual code.

✅ Ready to use

You are a senior JavaScript/TypeScript engineer specialized in testing.

Write complete Jest unit tests for the function I provide below.

Requirements:
1. **Coverage**: Test the happy path, all edge cases, and error paths.
2. **Edge cases to always include**:
   - Empty input (empty string, empty array, null, undefined)
   - Boundary values (0, -1, very large numbers, empty object {})
   - Invalid types (number passed where string expected, etc.)
3. **Mocking**:
   - Mock all external dependencies (fetch, axios, database calls, timers) using jest.mock() or jest.spyOn()
   - Do NOT make real network or DB calls in tests
4. **Structure**:
   - Use one top-level describe() block named after the function
   - Group related tests with nested describe() blocks (e.g., "when input is empty", "when API fails")
   - Each test name must start with "should"
5. **Assertions**:
   - Use expect().toBe() for primitives, expect().toEqual() for objects/arrays
   - For async functions, use async/await with expect().resolves / expect().rejects
6. **No external test libraries** other than Jest itself (no @testing-library, no sinon)

Output ONLY the test file content. No explanation, no markdown — just the raw code ready to save as `[functionName].test.js`.

Here is the function to test:
[PASTE FUNCTION HERE]

Example Output

Given this function as input:

❌ Input function

// fetchUser.js
export async function fetchUser(id) {
  if (!id) throw new Error("id is required");
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error("User not found");
  return res.json();
}

The prompt produces tests like:

✅ Generated test file

import { fetchUser } from "./fetchUser";

describe("fetchUser", () => {
  beforeEach(() => {
    global.fetch = jest.fn();
  });

  afterEach(() => {
    jest.resetAllMocks();
  });

  describe("when id is missing", () => {
    it("should throw when id is undefined", async () => {
      await expect(fetchUser(undefined)).rejects.toThrow("id is required");
    });

    it("should throw when id is null", async () => {
      await expect(fetchUser(null)).rejects.toThrow("id is required");
    });

    it("should throw when id is empty string", async () => {
      await expect(fetchUser("")).rejects.toThrow("id is required");
    });
  });

  describe("when API responds with an error", () => {
    it("should throw when response is not ok", async () => {
      global.fetch.mockResolvedValueOnce({ ok: false });
      await expect(fetchUser(1)).rejects.toThrow("User not found");
    });
  });

  describe("when API succeeds", () => {
    it("should return the parsed user object", async () => {
      const mockUser = { id: 1, name: "Alice" };
      global.fetch.mockResolvedValueOnce({
        ok: true,
        json: jest.fn().mockResolvedValueOnce(mockUser),
      });
      const result = await fetchUser(1);
      expect(result).toEqual(mockUser);
    });
  });
});

How to Customize It

Add TypeScript support

✅ TypeScript variant — add this line to the prompt

Use TypeScript. Import types from the source file. Output as `.test.ts`.

Target a React component instead of a plain function

✅ React Testing Library variant

Use @testing-library/react instead of plain Jest for DOM assertions.
Include render(), screen.getByRole(), and userEvent interactions.

Limit the number of tests

✅ Quick smoke-test variant

Write a maximum of 5 tests. Focus only on the happy path and 2 critical edge cases.
Skip low-priority boundary checks.

Frequently Asked Questions

Can I paste a whole module (multiple exports) instead of one function?

Yes, but add this instruction: "Generate one describe() block per exported function." For files with more than 5 exports, split them into separate prompts to avoid the AI cutting tests off mid-output.

Do the generated tests always pass?

~70–80% of generated tests run without changes in our tests. The most common fixes needed are: adjusting mock return value shapes to match your actual API, and updating import paths. Always run npx jest --watch after pasting and fix red tests before committing.

What's the best model to use for this prompt?

GPT-4o and Claude 3.5 Sonnet give the best results — they follow the output format consistently and generate accurate mocks. GPT-3.5 tends to skip edge cases and uses incorrect Jest APIs like jest.spyOn without restoring them. Avoid it for testing prompts.