Registry / testing / jest-mock

jest-mock

JSON →
library30.3.0jsnpmunverified

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.

npm install jest-mock
INSTALL
IMPORT
SIG · JEST-MOCK
J
jest-mock
testingjavascriptv30.3.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

jest.fn
const mockFunction = jest.fn((arg: string) => `mocked: ${arg}`);
const mockFunction = function() {}; // Not a Jest mock, won't have mock methods
jest.fn is available globally in Jest test environments. It creates a new mock function.
jest.spyOn
const spy = jest.spyOn(someObject, 'someMethod');
const spy = jest.spyOn(someObject.someMethod); // Must be (object, 'methodName')
jest.spyOn is available globally. It spies on an existing method, preserving its original implementation by default unless `mockImplementation` is called.
MockedFunction
import type { MockedFunction } from 'jest-mock'; // or import type { MockedFunction } from '@jest/globals';
Used for type safety when working with functions mocked by Jest, providing access to mock-specific properties like `mock`.
mocked
import { mocked } from 'jest-mock'; // or import { mocked } from '@jest/globals'; const data = mocked<ReturnType<typeof fetchApi>>(await fetchApi());
The `mocked` helper helps cast objects to their mocked type, asserting that properties like `mockRestore` or `mockClear` exist.

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`.

import { MockedFunction } from 'jest-mock'; // src/mathService.ts export const add = (a: number, b: number): number => a + b; export const multiply = (a: number, b: number): number => a * b; // src/calculator.ts import * as mathService from './mathService'; export const performAddition = (num1: number, num2: number): number => { return mathService.add(num1, num2); }; export const complexCalculation = (val1: number, val2: number): string => { const sum = mathService.add(val1, val2); const product = mathService.multiply(sum, 2); // We might want to mock multiply return `Result: ${product}`; }; // test/calculator.test.ts describe('calculator', () => { let addSpy: jest.SpyInstance<typeof mathService.add>; let mockMultiply: MockedFunction<typeof mathService.multiply>; beforeEach(() => { // Clears all mock calls, instances, and results from Jest mock functions. jest.clearAllMocks(); // Restores original implementations for all spies created with jest.spyOn. jest.restoreAllMocks(); // Create a spy for 'add' from mathService addSpy = jest.spyOn(mathService, 'add'); // Create a standalone mock function for 'multiply' mockMultiply = jest.fn<typeof mathService.multiply>(); // Replace the imported 'multiply' with our mock for this test file // Note: For actual module mocking, jest.mock('../src/mathService') is often used. // This is a direct replacement for demonstration. (mathService.multiply as MockedFunction<typeof mathService.multiply>) = mockMultiply; }); it('performAddition should call mathService.add and return the sum', () => { addSpy.mockReturnValueOnce(100); // Override implementation for this one call const result = performAddition(5, 7); expect(addSpy).toHaveBeenCalledTimes(1); expect(addSpy).toHaveBeenCalledWith(5, 7); expect(result).toBe(100); }); it('complexCalculation should use the mocked multiply function', () => { addSpy.mockReturnValueOnce(10); mockMultiply.mockReturnValueOnce(20); const result = complexCalculation(3, 7); // add(3,7) -> 10 (mocked) then multiply(10, 2) -> 20 (mocked) expect(addSpy).toHaveBeenCalledWith(3, 7); expect(mockMultiply).toHaveBeenCalledWith(10, 2); expect(result).toBe('Result: 20'); }); it('should allow dynamic mock implementations with jest.fn', () => { const processData = jest.fn((data: string) => `Processed: ${data.toUpperCase()}`); expect(processData('hello')).toBe('Processed: HELLO'); expect(processData).toHaveBeenCalledWith('hello'); }); });
jest --version
Debug
Known issues
breakingIn 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.
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.
affects: >=30.0.0
breakingJest 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.
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`.
affects: >=30.0.0
gotcha`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.
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.
affects: >=24.0.0
gotcha`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.
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.
affects: >=24.0.0
gotchaMixing 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.
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.
affects: >=24.0.0
Errors
Common errors & fixes
TypeError: someFunction.mockImplementation is not a function
Attempting to use Jest's mock-specific methods (like `mockImplementation`, `toHaveBeenCalled`) on a function that was not created by `jest.fn()` or `jest.spyOn()`.
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.
Cannot spyOn a non-existent property 'methodName' of object.
The method or property 'methodName' does not exist on the provided object when `jest.spyOn` is called.
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.
The module factory of `jest.mock()` is not returning a function.
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.
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') }));`
ReferenceError: Cannot access 'myVariable' before initialization
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.
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).
Upgrade
Version history
30.3.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
6 hits · last 30 days
node
6
Resources
jest-mock — npm install jest-mock · libregistry