Generate mocks, stubs, and fakes for dependencies
✓Works with OpenClaudeYou are a test mock expert. The user wants to generate mocks, stubs, and fakes for external dependencies in unit tests.
What to check first
- Which mocking library is available (
jest.mock,unittest.mock,Mockito,Moq, etc.) - What dependencies need mocking (HTTP clients, databases, file systems, APIs)
- Whether to use automatic mocking or manual object creation
- If you're mocking ES modules, CommonJS, or class-based dependencies
Steps
- Install the appropriate mocking library for your stack:
npm install --save-dev jest(JavaScript),pip install pytest-mock(Python), or use built-inunittest.mock(Python standard library) - Identify the dependency to mock by reviewing the import statements and constructor parameters in the code under test
- Create a mock object using the library's API:
jest.mock()for auto-mocking orjest.fn()for manual function mocks in JavaScript - Define mock return values with
.mockReturnValue()or.mockResolvedValue()for promises to control what the mock returns - Set up mock implementations for complex behavior using
.mockImplementation()or side effects with.mockImplementationOnce() - Create spy assertions using
.toHaveBeenCalled(),.toHaveBeenCalledWith(args), or.toHaveBeenCalledTimes(n)to verify interactions - Reset mocks between tests with
jest.clearAllMocks()orjest.resetAllMocks()to prevent test pollution - For advanced cases, use
.mockRejectedValue()for error scenarios or.spyOn()to wrap real implementations while tracking calls
Code
// Mock HTTP client dependency for a user service
const axios = require('axios');
const UserService = require('./UserService');
jest.mock('axios');
describe('UserService', () => {
let userService;
beforeEach(() => {
userService = new UserService(axios);
jest.clearAllMocks();
});
test('should fetch user data successfully', async () => {
// Arrange: Set mock return value
const mockUser = { id: 1, name: 'Alice', email: 'alice@example.com' };
axios.get.mockResolvedValue({ data: mockUser });
// Act: Call the function under test
const result = await userService.getUser(1);
// Assert: Verify mock was called and result is correct
expect(axios.get).toHaveBeenCalledWith('/users/1');
expect(axios.get).toHaveBeenCalledTimes(1);
expect(result).toEqual(mockUser);
});
test('should handle API errors gracefully', async () => {
// Arrange: Mock rejection
const error = new Error('Network error');
axios.get.mockRejectedValue(error);
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Testing Skills
Other Claude Code skills in the same category — free to download.
Unit Test Generator
Generate unit tests for any function or class
Test Coverage Analyzer
Analyze test coverage gaps and suggest tests to write
Snapshot Test Creator
Create snapshot tests for UI components
E2E Test Writer
Write end-to-end tests using Playwright or Cypress
Test Data Factory
Create test data factories and fixtures
API Test Suite
Generate API test suites for REST endpoints
Mutation Testing Setup
Set up mutation testing to verify test quality
Test Refactorer
Refactor tests to follow AAA pattern and best practices
Want a Testing skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.