generating-test-doubles
Generate mocks, stubs, spies, and fakes for dependency isolation. Use when creating mocks, stubs, or test isolation fixtures. Trigger with phrases like "generate mocks", "create test doubles", or "setup stubs".
Best use case
generating-test-doubles is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Generate mocks, stubs, spies, and fakes for dependency isolation. Use when creating mocks, stubs, or test isolation fixtures. Trigger with phrases like "generate mocks", "create test doubles", or "setup stubs".
Teams using generating-test-doubles should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/generating-test-doubles/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How generating-test-doubles Compares
| Feature / Agent | generating-test-doubles | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Generate mocks, stubs, spies, and fakes for dependency isolation. Use when creating mocks, stubs, or test isolation fixtures. Trigger with phrases like "generate mocks", "create test doubles", or "setup stubs".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Test Doubles Generator
## Overview
Generate mocks, stubs, spies, and fakes to isolate units under test from external dependencies. Supports Jest mocks, Sinon.js stubs, Python unittest.mock, Go interfaces, and testdouble.js patterns.
## Prerequisites
- Testing framework installed (Jest, Vitest, Mocha, pytest, JUnit 5, or Go testing)
- Mocking library available (Sinon.js, testdouble.js, unittest.mock, Mockito, or gomock)
- TypeScript `strict` mode enabled for type-safe mocks (if applicable)
- Source code with clear interface or class boundaries for dependency injection
## Instructions
1. Scan the codebase with Glob and Grep to identify modules with external dependencies (database clients, HTTP clients, file system access, third-party SDKs).
2. Read each module under test and catalog its dependency interfaces -- list every method signature, return type, and side effect.
3. Determine the appropriate test double type for each dependency:
- **Stub**: Returns canned data, no behavior verification (use for database queries returning fixed datasets).
- **Mock**: Verifies interactions -- call count, argument matching, call order (use for email senders, event emitters).
- **Spy**: Wraps real implementation while recording calls (use when partial behavior is needed).
- **Fake**: Lightweight working implementation (use for in-memory repositories replacing real databases).
4. Generate test double files following the project's existing test directory structure (e.g., `__mocks__/`, `test/doubles/`, `testutil/`).
5. For each test double, implement:
- Factory function or class matching the dependency interface exactly.
- Configurable return values via builder pattern or method chaining.
- Call recording for assertion (arguments, call count, call order).
- Reset/restore mechanism for cleanup between tests.
6. Wire test doubles into existing test files using the framework's dependency injection pattern (`jest.mock()`, `@patch`, constructor injection, or Go interface substitution).
7. Validate all test doubles compile and pass type checks by running `tsc --noEmit` or equivalent.
## Output
- Test double source files (one per dependency) placed in the project's mock directory
- Factory functions with TypeScript generics or equivalent type safety
- Jest `__mocks__` auto-mock modules where applicable
- Updated test files wired to use generated doubles instead of real dependencies
- Summary listing each double, its type (mock/stub/spy/fake), and the interface it replaces
## Error Handling
| Error | Cause | Solution |
|-------|-------|---------|
| `TypeError: X is not a function` | Mock missing a method from the real interface | Regenerate the double from the current interface definition; add the missing method |
| Mock leaking between tests | Shared mock state not reset in `afterEach` | Add `jest.restoreAllMocks()` or `sinon.restore()` in teardown hooks |
| Type mismatch on mock return value | Return type does not match interface contract | Use `as ReturnType<typeof fn>` or update the mock factory to return the correct type |
| Spy not recording calls | Spy created after the function was already bound | Create spies before the module under test imports the dependency |
| Over-mocking hides real bugs | Too many layers replaced with fakes | Limit mocks to true external boundaries (I/O, network); let pure logic run unmocked |
## Examples
**Jest mock factory for a UserRepository:**
```typescript
// __mocks__/userRepository.ts
export const createMockUserRepo = () => ({
findById: jest.fn().mockResolvedValue({ id: '1', name: 'Test User' }),
save: jest.fn().mockResolvedValue(undefined),
delete: jest.fn().mockResolvedValue(true),
});
```
**Python unittest.mock patch for an HTTP client:**
```python
from unittest.mock import patch, MagicMock
@patch('myapp.client.requests.get')
def test_fetch_data(mock_get):
mock_get.return_value = MagicMock(status_code=200, json=lambda: {"key": "value"}) # HTTP 200 OK
result = fetch_data("https://api.example.com/data")
assert result == {"key": "value"}
mock_get.assert_called_once()
```
**Go interface-based fake:**
```go
type FakeStore struct {
data map[string]string
}
func (f *FakeStore) Get(key string) (string, error) {
v, ok := f.data[key]
if !ok { return "", ErrNotFound }
return v, nil
}
```
## Resources
- Jest Manual Mocks: https://jestjs.io/docs/manual-mocks
- Sinon.js Stubs, Mocks, Spies: https://sinonjs.org/
- Python unittest.mock: https://docs.python.org/3/library/unittest.mock.html
- Mockito (Java): https://site.mockito.org/
- gomock (Go): https://github.com/uber-go/mock
- Martin Fowler, "Mocks Aren't Stubs": https://martinfowler.com/articles/mocksArentStubs.htmlRelated Skills
test-skill
Test skill for E2E validation. Trigger with "run test skill" or "execute test". Use this skill when testing skill activation and tool permissions.
testing-visual-regression
Detect visual changes in UI components using screenshot comparison. Use when detecting unintended UI changes or pixel differences. Trigger with phrases like "test visual changes", "compare screenshots", or "detect UI regressions".
generating-unit-tests
Test automatically generate comprehensive unit tests from source code covering happy paths, edge cases, and error conditions. Use when creating test coverage for functions, classes, or modules. Trigger with phrases like "generate unit tests", "create tests for", or "add test coverage".
generating-test-reports
Generate comprehensive test reports with metrics, coverage, and visualizations. Use when performing specialized testing. Trigger with phrases like "generate test report", "create test documentation", or "show test metrics".
orchestrating-test-execution
Test coordinate parallel test execution across multiple environments and frameworks. Use when performing specialized testing. Trigger with phrases like "orchestrate tests", "run parallel tests", or "coordinate test execution".
managing-test-environments
Test provision and manage isolated test environments with configuration and data. Use when performing specialized testing. Trigger with phrases like "manage test environment", "provision test env", or "setup test infrastructure".
generating-test-data
Generate realistic test data including edge cases and boundary conditions. Use when creating realistic fixtures or edge case test data. Trigger with phrases like "generate test data", "create fixtures", or "setup test database".
analyzing-test-coverage
Analyze code coverage metrics and identify untested code paths. Use when analyzing untested code or coverage gaps. Trigger with phrases like "analyze coverage", "check test coverage", or "find untested code".
managing-snapshot-tests
Create and validate component snapshots for UI regression testing. Use when performing specialized testing. Trigger with phrases like "update snapshots", "test UI snapshots", or "validate component snapshots".
running-smoke-tests
Execute fast smoke tests validating critical functionality after deployment. Use when performing specialized testing. Trigger with phrases like "run smoke tests", "quick validation", or "test critical paths".
performing-security-testing
Test automate security vulnerability testing covering OWASP Top 10, SQL injection, XSS, CSRF, and authentication issues. Use when performing security assessments, penetration tests, or vulnerability scans. Trigger with phrases like "scan for vulnerabilities", "test security", or "run penetration test".
tracking-regression-tests
Track and manage regression test suites across releases. Use when performing specialized testing. Trigger with phrases like "track regressions", "manage regression suite", or "validate against baseline".