// math.js
export function add(a, b) {
return a + b;
}
// math.test.js
import * as math from './math';
test('mock add function', () => {
jest.spyOn(math, 'add').mockImplementation(() => 42);
const result = math.add(1, 2);
console.log(result);
});The jest.spyOn replaces the original add function with a mock that returns 42 regardless of input. So calling math.add(1, 2) returns 42.
// greet.js
export default function greet(name) {
return `Hello, ${name}!`;
}
// greet.test.js
import greet from './greet';
jest.mock('./greet', () => {
// Fill in the mock implementation
});When mocking a default export, the mock must return an object with a default property that is the mocked function.
// utils.js
export function fetchData() {
return 'real data';
}
// app.js
import { fetchData } from './utils';
export function getData() {
return fetchData();
}
// app.test.js
import { getData } from './app';
import * as utils from './utils';
jest.mock('./utils');
test('mock fetchData', () => {
utils.fetchData.mockReturnValue('mocked data');
const result = getData();
console.log(result);
});The getData function imports fetchData before the mock is applied, so it uses the original function. Jest mocks must be set up before importing the module that uses the function.
const utils = {
getNumber: () => 5
};
jest.mock('./utils', () => ({
getNumber: jest.fn(() => 10)
}));
import { getNumber } from './utils';
console.log(getNumber());
getNumber.mockReset();
console.log(getNumber());mockReset clears the mock implementation, so the function returns undefined after reset.
jest.mock can replace the entire module by returning an object with named exports mocked as jest.fn(). This is the standard way to mock named exports.
