{"id":13378,"library":"jest-mock","title":"Jest Mock Utilities","description":"The `jest-mock` package is a fundamental component of the Jest testing framework, providing the core utilities for creating, controlling, and asserting on mock functions, spies, and module mocks. Currently stable at version 30.3.0, it's released as part of the broader Jest project, which is evolving towards more frequent major updates after a significant three-year cycle for Jest 30. This library enables developers to isolate units of code for testing by replacing dependencies with controlled, test-specific implementations. Its key differentiators include deep integration with the Jest runner, comprehensive APIs for various mocking scenarios (functions, objects, modules), automatic mock resets, and robust TypeScript definitions, all designed to facilitate predictable and efficient unit and integration testing.","status":"active","version":"30.3.0","language":"javascript","source_language":"en","source_url":"https://github.com/jestjs/jest","tags":["javascript","typescript"],"install":[{"cmd":"npm install jest-mock","lang":"bash","label":"npm"},{"cmd":"yarn add jest-mock","lang":"bash","label":"yarn"},{"cmd":"pnpm add jest-mock","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"jest.fn is available globally in Jest test environments. It creates a new mock function.","wrong":"const mockFunction = function() {}; // Not a Jest mock, won't have mock methods","symbol":"jest.fn","correct":"const mockFunction = jest.fn((arg: string) => `mocked: ${arg}`);"},{"note":"jest.spyOn is available globally. It spies on an existing method, preserving its original implementation by default unless `mockImplementation` is called.","wrong":"const spy = jest.spyOn(someObject.someMethod); // Must be (object, 'methodName')","symbol":"jest.spyOn","correct":"const spy = jest.spyOn(someObject, 'someMethod');"},{"note":"Used for type safety when working with functions mocked by Jest, providing access to mock-specific properties like `mock`.","symbol":"MockedFunction","correct":"import type { MockedFunction } from 'jest-mock';\n// or\nimport type { MockedFunction } from '@jest/globals';"},{"note":"The `mocked` helper helps cast objects to their mocked type, asserting that properties like `mockRestore` or `mockClear` exist.","symbol":"mocked","correct":"import { mocked } from 'jest-mock';\n// or\nimport { mocked } from '@jest/globals';\nconst data = mocked<ReturnType<typeof fetchApi>>(await fetchApi());"}],"quickstart":{"code":"import { MockedFunction } from 'jest-mock';\n\n// src/mathService.ts\nexport const add = (a: number, b: number): number => a + b;\nexport const multiply = (a: number, b: number): number => a * b;\n\n// src/calculator.ts\nimport * as mathService from './mathService';\n\nexport const performAddition = (num1: number, num2: number): number => {\n  return mathService.add(num1, num2);\n};\n\nexport const complexCalculation = (val1: number, val2: number): string => {\n  const sum = mathService.add(val1, val2);\n  const product = mathService.multiply(sum, 2); // We might want to mock multiply\n  return `Result: ${product}`;\n};\n\n// test/calculator.test.ts\ndescribe('calculator', () => {\n  let addSpy: jest.SpyInstance<typeof mathService.add>;\n  let mockMultiply: MockedFunction<typeof mathService.multiply>;\n\n  beforeEach(() => {\n    // Clears all mock calls, instances, and results from Jest mock functions.\n    jest.clearAllMocks();\n    // Restores original implementations for all spies created with jest.spyOn.\n    jest.restoreAllMocks(); \n\n    // Create a spy for 'add' from mathService\n    addSpy = jest.spyOn(mathService, 'add');\n\n    // Create a standalone mock function for 'multiply'\n    mockMultiply = jest.fn<typeof mathService.multiply>();\n    // Replace the imported 'multiply' with our mock for this test file\n    // Note: For actual module mocking, jest.mock('../src/mathService') is often used.\n    // This is a direct replacement for demonstration.\n    (mathService.multiply as MockedFunction<typeof mathService.multiply>) = mockMultiply;\n  });\n\n  it('performAddition should call mathService.add and return the sum', () => {\n    addSpy.mockReturnValueOnce(100); // Override implementation for this one call\n    const result = performAddition(5, 7);\n    expect(addSpy).toHaveBeenCalledTimes(1);\n    expect(addSpy).toHaveBeenCalledWith(5, 7);\n    expect(result).toBe(100);\n  });\n\n  it('complexCalculation should use the mocked multiply function', () => {\n    addSpy.mockReturnValueOnce(10);\n    mockMultiply.mockReturnValueOnce(20);\n\n    const result = complexCalculation(3, 7); // add(3,7) -> 10 (mocked) then multiply(10, 2) -> 20 (mocked)\n\n    expect(addSpy).toHaveBeenCalledWith(3, 7);\n    expect(mockMultiply).toHaveBeenCalledWith(10, 2);\n    expect(result).toBe('Result: 20');\n  });\n\n  it('should allow dynamic mock implementations with jest.fn', () => {\n    const processData = jest.fn((data: string) => `Processed: ${data.toUpperCase()}`);\n    expect(processData('hello')).toBe('Processed: HELLO');\n    expect(processData).toHaveBeenCalledWith('hello');\n  });\n});","lang":"typescript","description":"Demonstrates creating mock functions with `jest.fn`, spying on existing functions with `jest.spyOn`, overriding mock implementations, and asserting on mock calls and return values, including type safety with `MockedFunction`."},"warnings":[{"fix":"Review your `jest.config.js` or CLI arguments. If you need mock state to persist, explicitly set `clearMocks: false`. Otherwise, ensure your tests are properly isolated and do not depend on previous mock state.","message":"In Jest 30, the default for `clearMocks` in the Jest configuration changed to `true`. This means that mock calls, instances, and results are automatically cleared before each test by default. If your tests relied on mock state persisting across multiple tests or setup files, they might break.","severity":"breaking","affected_versions":">=30.0.0"},{"fix":"Update tests to align with the `modern` timer implementation. If necessary, you can revert to the legacy implementation by calling `jest.useFakeTimers('legacy')` or configuring `timers: 'legacy'` in `jest.config.js`.","message":"Jest 30 changed the default `useFakeTimers` implementation to `modern`. This affects how `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`, `setImmediate`, `clearImmediate`, and `Date` behave under fake timers. Older tests might exhibit different timing behaviors.","severity":"breaking","affected_versions":">=30.0.0"},{"fix":"If your mock factory needs access to variables, define them outside the test file or use `jest.doMock` within a `beforeEach` or `test` block, which is not hoisted but is more complex for module mocking. For dynamic values in mocks, consider using `jest.mock` with a factory that returns a function that then uses context from the test.","message":"`jest.mock` calls are hoisted to the top of the file before any `import` statements are executed. This means any variables defined within your test file are not available within the factory function passed to `jest.mock`, as the factory runs in a different scope.","severity":"gotcha","affected_versions":">=24.0.0"},{"fix":"Ensure the target method/property is defined on the object before calling `jest.spyOn`. For dynamic methods or properties that might not exist, consider using `jest.fn()` to create a standalone mock and inject it, or using `Object.defineProperty` to add the property before spying.","message":"`jest.spyOn` creates a mock on an *existing* property of an object. If the method or property you're trying to spy on doesn't exist on the object at the time `jest.spyOn` is called, it will throw an error.","severity":"gotcha","affected_versions":">=24.0.0"},{"fix":"Prefer a consistent module system (either all ESM `import`/`export` or all CommonJS `require`/`module.exports`) within a given test file and its dependencies where mocking is involved. When mocking ESM, use dynamic `import()` or the `unstable_mockModule` API where appropriate.","message":"Mixing CommonJS `require()` with ESM `import` statements for mocking can lead to unexpected behavior, especially when dealing with module hoisting and the way Jest resolves modules. While Jest has improved ESM support, specific mocking patterns might still behave differently.","severity":"gotcha","affected_versions":">=24.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `someFunction` is a Jest mock by creating it with `jest.fn()` or `jest.spyOn()`. If it's an imported function, either spy on it or use `jest.mock()` to replace the module.","cause":"Attempting to use Jest's mock-specific methods (like `mockImplementation`, `toHaveBeenCalled`) on a function that was not created by `jest.fn()` or `jest.spyOn()`.","error":"TypeError: someFunction.mockImplementation is not a function"},{"fix":"Verify the spelling of 'methodName' and ensure the property exists on `object` before `jest.spyOn` is invoked. If the property is created dynamically, ensure it's created *before* the spy. For non-existent properties you want to mock, use `jest.fn()` directly.","cause":"The method or property 'methodName' does not exist on the provided object when `jest.spyOn` is called.","error":"Cannot spyOn a non-existent property 'methodName' of object."},{"fix":"Ensure your `jest.mock` factory function explicitly returns an object that represents the mocked module's exports, or a function if you're mocking a default export that is a function. Example: `jest.mock('./my-module', () => ({ default: jest.fn(() => 'mocked') }));`","cause":"When using `jest.mock(moduleName, factory)`, the `factory` function must return a value (often an object with mocked exports). Returning `undefined` or a non-object/non-function can cause this.","error":"The module factory of `jest.mock()` is not returning a function."},{"fix":"Define variables needed by `jest.mock` factories in a separate file imported by the test, or pass them as parameters if using `jest.doMock` within a `beforeEach` block (which avoids hoisting but changes the mocking scope).","cause":"This error often occurs when a `jest.mock` factory function attempts to use a variable defined in the same test file. Due to hoisting, the `jest.mock` factory executes before other variables in the file are initialized.","error":"ReferenceError: Cannot access 'myVariable' before initialization"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"jest","cli_version":null}