3. Jest: Mocks, Spies, and Function Testing
Mocks and spies are essential tools for testing functions that have dependencies. They allow you to isolate the code you're testing by replacing dependencies with controlled implementations. This module covers Jest's mocking capabilities, including jest.fn(), jest.spyOn(), and automatic mocking.
The key insight is that mocks let you test code in isolation. By mocking dependencies, you can test a function's behavior without worrying about its dependencies. Mocks also let you verify that functions were called correctly — with the right arguments and the expected number of times. Understanding mocks is essential for testing complex code.
This module covers creating mocks, spying on functions, verifying calls, and mocking modules.
Creating Mocks with jest.fn()
jest.fn() creates a mock function. Mock functions track calls, arguments, and return values. You can also set return values or implementations. Mock functions are the foundation of Jest's mocking system. They're used to replace dependencies and verify interactions.
Common mock uses: replacing API calls, replacing database queries, replacing external services, and verifying function calls. Mock functions can be used standalone or as replacements for imported modules.
Spying with jest.spyOn()
jest.spyOn() wraps an existing method and creates a spy. The spy tracks calls while preserving the original behavior. This is useful for testing that methods are called correctly without changing their implementation. You can also use mockImplementation to override the behavior.
Spies are ideal for testing: logging calls, event handlers, lifecycle methods, and external API calls. They let you verify that certain functions were called without changing how they work.
// Creating a mock function const mockFn = jest.fn(); // Mock returns a value mockFn.mockReturnValue(42); console.log(mockFn()); // 42 // Mock has a custom implementation const mockAdd = jest.fn().mockImplementation((a, b) => a + b); console.log(mockAdd(2, 3)); // 5 // Verify calls expect(mockAdd).toHaveBeenCalled(); expect(mockAdd).toHaveBeenCalledWith(2, 3); expect(mockAdd).toHaveBeenCalledTimes(1); // Spying on an object method const user = { getName: () => 'Alice', setName: (name) => { /* implementation */ } }; const spy = jest.spyOn(user, 'getName'); console.log(user.getName()); // 'Alice' (original behavior preserved) expect(spy).toHaveBeenCalledTimes(1); // Override implementation spy.mockImplementation(() => 'Bob'); console.log(user.getName()); // 'Bob' // Restore original behavior spy.mockRestore();
Mocking Modules
Jest can mock entire modules using jest.mock(). This replaces the module's exports with mock implementations. Module mocking is essential for testing code that imports external dependencies like API clients, database drivers, or third-party libraries.
There are two types of module mocks: automatic (Jest creates a mock with all methods as jest.fn()) and manual (you provide the mock implementation). Use automatic mocks for simple dependencies and manual mocks for complex ones.
// api.js - the module to mock export const fetchUser = (id) => fetch(`/users/${id}`); export const saveUser = (user) => fetch('/users', { method: 'POST', body: user }); // userService.js - using the API module import { fetchUser, saveUser } from './api'; export const getUser = async (id) => { const response = await fetchUser(id); return response.json(); }; // userService.test.js - testing with mocked API import { fetchUser, saveUser } from './api'; import { getUser } from './userService'; jest.mock('./api'); describe('UserService', () => { test('getUser fetches and parses user data', async () => { const mockUser = { id: 1, name: 'Alice' }; const mockResponse = { json: jest.fn().mockResolvedValue(mockUser) }; // Mock fetchUser to return the mock response fetchUser.mockResolvedValue(mockResponse); const result = await getUser(1); expect(fetchUser).toHaveBeenCalledWith(1); expect(mockResponse.json).toHaveBeenCalled(); expect(result).toEqual(mockUser); }); });
Try It Yourself: Working with Mocks
Follow these steps to practice using mocks in Jest.
Step 1: Create the files// api.js<br>export const fetchUser = (id) => {<br> return fetch(`https://api.example.com/users/${id}`);<br>};<br><br>export const saveUser = (user) => {<br> return fetch(<strong><code>https://api.example.com/users, {
method: POST,
body: JSON.stringify(user),
headers: { Content-Type: application/json }
});
};// userService.js<br>import { fetchUser, saveUser } from <strong><code>./api;
export const getUserName = async (id) => {
const response = await fetchUser(id);
const user = await response.json();
return user.name;
};
export const createUser = async (userData) => {
const response = await saveUser(userData);
return response.json();
};
Step 2: Write the test// userService.test.js<br>import { fetchUser, saveUser } from <strong><code>./api;
import { getUserName, createUser } from ./userService;
jest.mock(./api);
describe(UserService, () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('getUserName fetches and returns user name', async () => {
const mockUser = { id: 1, name: Alice };
const mockResponse = {
json: jest.fn().mockResolvedValue(mockUser)
};
fetchUser.mockResolvedValue(mockResponse);
const name = await getUserName(1);
expect(fetchUser).toHaveBeenCalledWith(1);
expect(mockResponse.json).toHaveBeenCalled();
expect(name).toBe(Alice);
});
test('createUser saves user and returns response', async () => {
const userData = { name: Bob };
const mockResponse = {
json: jest.fn().mockResolvedValue({ id: 2, ...userData })
};
saveUser.mockResolvedValue(mockResponse);
const result = await createUser(userData);
expect(saveUser).toHaveBeenCalledWith(userData);
expect(result).toEqual({ id: 2, ...userData });
});
test(handles API errors, async () => {
const error = new Error(Network error);
fetchUser.mockRejectedValue(error);
await expect(getUserName(1)).rejects.toThrow(Network error);
});
});
Step 3: Run the testsnpx jest
Try It Yourself: Create a mock for a function that fetches data from a database. Write tests that verify the function handles success and failure cases.
Knowledge Check
Ready to test your understanding of 3. Jest: Mocks, Spies, and Function Testing?