Learn the concept
Mocking Functions, Modules, and APIs
Jest provides jest.fn() for mock functions, jest.mock() for modules, and jest.spyOn() for spying on methods. For API calls, mock fetch/axios or use libraries like MSW. Mocks isolate code under test and allow controlling dependencies.
Mock Types:
jest.fn(): Create mock function
jest.mock(): Mock entire module
jest.spyOn(): Spy on existing method
API Mocking:
describe('Mock functions', () => {
test('basic mock function', () => {
const mockFn = jest.fn();
mockFn('hello');
mockFn('world');
expect(mockFn).toHaveBeenCalledTimes(2);
expect(mockFn).toHaveBeenCalledWith('hello');
expect(mockFn).toHaveBeenLastCalledWith('world');
});
test('mock with return value', () => {
const mockFn = jest.fn()
.mockReturnValue('default')
.mockReturnValueOnce('first')
.mockReturnValueOnce('second');
expect(mockFn()).toBe('first');
expect(mockFn()).toBe('second');
expect(mockFn()).toBe('default');
});
test('mock with implementation', () => {
const mockFn = jest.fn((x) => x * 2);
expect(mockFn(5)).toBe(10);
expect(mockFn).toHaveBeenCalledWith(5);
});
test('mock async function', async () => {
const mockFn = jest.fn().mockResolvedValue({ id: 1, name: 'Alice' });
const result = await mockFn();
expect(result.name).toBe('Alice');
});
});Using `jest.mock()` to mock the API module (e.g., `axios`, `fetch`) and control its return values, ensuring that tests are fast, isolated, and don't rely on a live backend.
Employing `jest.fn()` to create mock functions for each dependency, allowing the developer to verify that the function under test calls its dependencies with the correct arguments and handles their return values as expected.
Using `jest.spyOn(console, 'log').mockImplementation(() => {})` to spy on `console.log`, assert that it was called with the expected arguments, and prevent test output from being cluttered by actual console messages.
Build a simple Todo application that fetches todos from an API. Use `jest.mock()` to mock the API calls and test various scenarios like successful data fetch, error handling, and empty data.
Implement a user authentication function that depends on a password hashing utility and a user database service. Use `jest.fn()` to mock these dependencies and test the authentication logic in isolation.
Stripe's client-side SDKs involve intricate logic for handling payments and interacting with their API. They extensively use Jest's mocking capabilities to test these SDKs in isolation, ensuring that every scenario, including network errors and various payment outcomes, is reliably covered without actual API calls.
Developers building extensions for VS Code often rely on mocking. For example, mocking VS Code's API (`vscode` module) allows them to test their extension's commands, UI interactions, and data processing logic without needing to run a full VS Code instance.