Skip to main content

Jest Mock Generator

Generate Jest mock and spy code instantly. Choose module mocks, class mocks, function mocks, spies with custom behaviors, or fake timer setups — with optional TypeScript type assertions.

✓ Module / Class / Function / Spy / Timer ✓ TypeScript support ✓ All mock behaviors

Frequently Asked Questions

What is the difference between jest.mock() and jest.spyOn()?▼

jest.mock() replaces an entire module with a mocked version — great for isolating tests from external dependencies. jest.spyOn() wraps an existing method on an object, letting you observe calls and optionally change behavior while preserving the original. Use jest.mock() for heavy isolation, jest.spyOn() for lighter observation with restore capability.

When should I use mockReturnValue vs mockImplementation?▼

Use mockReturnValue when the mock simply needs to return a fixed value — it's concise and readable. Use mockImplementation when you need conditional logic, access to arguments, or multiple return paths. Use mockReturnValueOnce for chained sequential values: mock.mockReturnValueOnce('first').mockReturnValueOnce('second').

How do I mock async functions?▼

Use mockResolvedValue (equivalent to mockReturnValue(Promise.resolve(value))) or mockRejectedValue (equivalent to mockReturnValue(Promise.reject(error))). For async spies, use jest.spyOn(object, 'method').mockResolvedValue(data). In tests, use await to resolve the promise and assert the result.

How do I mock a class constructor and its methods?▼

Call jest.mock('./MyClass') to auto-mock the class. Then use MyClass as jest.MockedClass<typeof MyClass> to access mock methods. Override methods via MyClass.prototype.method = jest.fn() or use mockImplementation on the constructor to return a custom object. Always call mockClear() in beforeEach to reset call counts.

What does mockRestore() do and when should I use it?▼

mockRestore() restores a jest.spyOn() spy back to its original implementation. It only works on spies created with jest.spyOn() — not manual jest.fn() mocks. Call it in afterEach to prevent test pollution. If you forget to restore, later tests may interact with stale spies. jest.restoreAllMocks() in afterEach restores all spies at once.

How do I reset or clear mocks between tests?▼

Use jest.clearAllMocks() to clear call history (calls, instances, results) without removing implementations. jest.resetAllMocks() also removes mock implementations, returning jest.fn(). jest.restoreAllMocks() restores spies created with jest.spyOn(). Configure these automatically in jest.config.js with clearMocks, resetMocks, or restoreMocks: true.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Jest Coverage Config Generator Jest Testing Framework Guide Jest to Vitest Migrator SQL to TypeScript Types TypeScript Discriminated Union Builder TypeScript Playground TypeScript to JavaScript Converter TypeScript tsconfig.json Generator JS Prototype Chain Visualizer Vitest Guide — Vite-native Testing Neon DB Query Builder Code Tools JavaScript Formatter & Minifier JSON to TypeScript Interface Prettier Config Generator Cypress Frontend Testing Guide Zustand Store Builder GraphQL Client Configurator Axios Interceptor Builder API Test Case Generator Turso Edge DB Explorer AI Unit Test Generator — Pro Tool API Response Mock Generator HTTP API Tester ESLint Config Generator Regex Visualizer Regex Tester Pro Regex Tester Biome Config Generator Vitest Configuration Generator Regex Flags Explainer k6 Load Test Script Generator Playwright E2E Test Generator Bundle Size Estimator JavaScript Memory Leak Detector NPM Bundle Size Estimator Playwright E2E Testing Guide Mock Service Worker (MSW) API Mocking Guide AWS CDK Infrastructure as Code Guide Pulumi Modern IaC Guide JSON Schema to Zod Converter Drizzle Schema Generator Playwright Test Generator Test Coverage Calculator Pulumi Stack Config Generator Bundle Size Impact Calculator HTML5 Canvas API Playground Game Loop Calculator Bezier Curve Editor Particle System Config Generator Prompt Injection Tester TanStack Query Config Builder SWR Config Generator Jotai Atom Explorer OpenAI Function Calling Generator React Component Generator

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →