Generate Jest mock function tests with spies, stubs, and module mocking
Generate comprehensive Jest tests using mock functions, spies, stubs, and module mocking patterns based on official Jest documentation.
This skill helps you create Jest tests that use mock functions to:
When the user asks you to create Jest mocks or test with mock functions, follow these steps:
First, analyze the code under test:
Select the appropriate technique:
**Simple Mock Function (jest.fn())**
**Module Mocking (jest.mock())**
**Partial Module Mocking**
**Manual Mock Implementation**
Create the mock with appropriate configuration:
```javascript
// Simple spy
const mockFn = jest.fn();
// Mock with return value
const mockFn = jest.fn().mockReturnValue(42);
// Mock with different returns per call
const mockFn = jest.fn()
.mockReturnValueOnce(10)
.mockReturnValueOnce('x')
.mockReturnValue(true);
// Mock with implementation
const mockFn = jest.fn((x, y) => x + y);
// Mock async function
const mockFn = jest.fn().mockResolvedValue({ data: 'result' });
```
For external dependencies:
```javascript
import axios from 'axios';
import Users from './users';
jest.mock('axios');
test('should fetch users', () => {
const users = [{ name: 'Bob' }];
const resp = { data: users };
axios.get.mockResolvedValue(resp);
return Users.all().then(data => expect(data).toEqual(users));
});
```
For partial mocking:
```javascript
jest.mock('../foo-bar-baz', () => {
const originalModule = jest.requireActual('../foo-bar-baz');
return {
__esModule: true,
...originalModule,
default: jest.fn(() => 'mocked baz'),
foo: 'mocked foo',
};
});
```
Inspect mock state to verify behavior:
```javascript
// Check number of calls
expect(mockFn.mock.calls).toHaveLength(2);
// Check call arguments
expect(mockFn.mock.calls[0][0]).toBe('first arg');
expect(mockFn.mock.calls[0][1]).toBe('second arg');
// Check return values
expect(mockFn.mock.results[0].value).toBe(42);
// Check this context
expect(mockFn.mock.contexts[0]).toBe(element);
// Check constructor instances
expect(mockFn.mock.instances.length).toBe(2);
expect(mockFn.mock.instances[0].name).toBe('test');
// Check last call
expect(mockFn.mock.lastCall[0]).toBe('test');
```
Prefer Jest's custom matchers for cleaner assertions:
```javascript
// Function was called
expect(mockFn).toHaveBeenCalled();
// Called with specific args
expect(mockFn).toHaveBeenCalledWith(arg1, arg2);
// Last call had specific args
expect(mockFn).toHaveBeenLastCalledWith(arg1, arg2);
// Snapshot all calls
expect(mockFn).toMatchSnapshot();
```
For better error messages in test output:
```javascript
const myMockFn = jest.fn()
.mockReturnValue('default')
.mockName('add42');
```
Consider these patterns:
**Chained methods:**
```javascript
const myObj = {
myMethod: jest.fn().mockReturnThis(),
};
```
**Complex sequential behavior:**
```javascript
const myMockFn = jest.fn()
.mockImplementationOnce(cb => cb(null, true))
.mockImplementationOnce(cb => cb(null, false));
```
**Fallback to default implementation:**
```javascript
const myMockFn = jest.fn(() => 'default')
.mockImplementationOnce(() => 'first call')
.mockImplementationOnce(() => 'second call');
```
1. **Mock at the Right Level**: Mock external boundaries (APIs, databases), not internal logic
2. **Avoid Over-Mocking**: Keep real implementations when possible using partial mocks
3. **Name Your Mocks**: Use `.mockName()` for easier debugging
4. **Use Custom Matchers**: Prefer `toHaveBeenCalledWith()` over manual `.mock.calls` inspection
5. **Reset Between Tests**: Clear mock state with `mockFn.mockClear()` or configure `clearMocks: true` in jest.config
6. **Mock Return Values**: Use `mockResolvedValue()` for promises, `mockReturnValue()` for sync
7. **Test Isolation**: Each test should set up its own mocks independently
```javascript
// forEach.test.js
import { forEach } from './forEach';
const mockCallback = jest.fn(x => 42 + x);
test('forEach mock function', () => {
forEach([0, 1], mockCallback);
// Verify called twice
expect(mockCallback.mock.calls).toHaveLength(2);
// Verify first call args
expect(mockCallback.mock.calls[0][0]).toBe(0);
// Verify second call args
expect(mockCallback.mock.calls[1][0]).toBe(1);
// Verify return value
expect(mockCallback.mock.results[0].value).toBe(42);
});
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/jest-mock-functions/raw