Performance: Mocking modules and functions
Mocking affects test execution speed and memory usage during development but does not impact production page load or rendering.
jest.mock('big-module', () => ({ smallFunction: jest.fn(), })); // mock only needed functions with lightweight stubs
import * as bigModule from 'big-module'; jest.mock('big-module'); // mock entire module with heavy default mocks
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Mock entire large module | 0 | 0 | 0 | [X] Bad |
| Mock only needed functions | 0 | 0 | 0 | [OK] Good |
utils using Jest?jest.mock('moduleName') to mock entire modules.jest.mock() function with the module name.console.log(fetchData()) after mocking?import * as api from './api';
jest.mock('./api', () => ({
fetchData: () => 'mocked data'
}));
console.log(api.fetchData());jest.mock call replaces the entire './api' module with the provided object.fetchData returns the string 'mocked data'.import * as math from './math'; jest.spyOn(math, 'add'); math.add.mockReturnValue(10); console.log(math.add(2, 3));
mockReturnValue(10) on the spy sets the return value to 10.sendEmail function from the notifications module to return true during tests, but keep other functions real. Which is the best approach?Pass the test and this pattern moves unknown