Claude
Skills
Sign in
Back

mock-generator

Included with Lifetime
$97 forever

Generates test mocks, stubs, and fixtures for testing (Jest, Vitest, pytest, etc.). Use when user asks to "create mock", "generate stub", "mock function", "test fixtures", or "mock API response".

Backend & APIs

What this skill does


# Mock Generator

Automatically generates test mocks, stubs, and fixtures for various testing frameworks.

## When to Use

- "Create a mock for this function"
- "Generate test fixtures"
- "Mock this API response"
- "Create stubs for testing"
- "Generate mock data"
- "Mock this class/module"

## Instructions

### 1. Identify What to Mock

Ask the user or analyze code to determine:
- What needs to be mocked (function, class, API, database, etc.)
- Which testing framework is used
- What the mock behavior should be
- What data the mock should return

Scan for testing framework:

```bash
# Check package.json for testing framework
grep -E "(jest|vitest|mocha|jasmine|pytest|unittest|minitest)" package.json

# Check for test files
find . -name "*.test.*" -o -name "*.spec.*" -o -name "test_*.py"
```

### 2. Determine Mock Type

**Function Mocks:**
- Simple return value
- Multiple return values
- Implementations
- Spy on function calls

**API Mocks:**
- HTTP request/response
- WebSocket messages
- GraphQL queries
- REST endpoints

**Class Mocks:**
- Instance methods
- Static methods
- Properties
- Constructors

**Module Mocks:**
- Entire module
- Partial module
- Default exports
- Named exports

### 3. Generate Mocks by Framework

## JavaScript/TypeScript Mocks

### Jest Mocks

**Simple Function Mock:**
```javascript
// Mock a simple function
const mockFn = jest.fn()
mockFn.mockReturnValue(42)

// Use in test
test('uses mocked function', () => {
  expect(mockFn()).toBe(42)
  expect(mockFn).toHaveBeenCalled()
})
```

**Function with Different Return Values:**
```javascript
const mockFn = jest.fn()
  .mockReturnValueOnce('first')
  .mockReturnValueOnce('second')
  .mockReturnValue('default')

expect(mockFn()).toBe('first')
expect(mockFn()).toBe('second')
expect(mockFn()).toBe('default')
```

**Mock Implementation:**
```javascript
const mockFn = jest.fn((x, y) => x + y)

expect(mockFn(1, 2)).toBe(3)
expect(mockFn).toHaveBeenCalledWith(1, 2)
```

**Module Mock:**
```javascript
// __mocks__/axios.js
export default {
  get: jest.fn(() => Promise.resolve({ data: {} })),
  post: jest.fn(() => Promise.resolve({ data: {} })),
}

// In test file
jest.mock('axios')
import axios from 'axios'

test('fetches data', async () => {
  axios.get.mockResolvedValue({ data: { name: 'John' } })

  const result = await fetchUser(1)

  expect(result.name).toBe('John')
  expect(axios.get).toHaveBeenCalledWith('/users/1')
})
```

**Class Mock:**
```javascript
// Mock a class
jest.mock('./Database')
import Database from './Database'

Database.mockImplementation(() => ({
  query: jest.fn().mockResolvedValue([{ id: 1, name: 'John' }]),
  connect: jest.fn().mockResolvedValue(true),
  disconnect: jest.fn().mockResolvedValue(true),
}))

test('uses database', async () => {
  const db = new Database()
  const users = await db.query('SELECT * FROM users')

  expect(users).toHaveLength(1)
  expect(db.query).toHaveBeenCalled()
})
```

**Partial Mock:**
```javascript
// Mock only specific methods
import * as utils from './utils'

jest.spyOn(utils, 'fetchData').mockResolvedValue({ data: 'mocked' })

test('uses mocked method', async () => {
  const result = await utils.fetchData()
  expect(result.data).toBe('mocked')
})
```

### Vitest Mocks

**Function Mock:**
```javascript
import { vi, expect, test } from 'vitest'

const mockFn = vi.fn()
mockFn.mockReturnValue(42)

test('uses mock', () => {
  expect(mockFn()).toBe(42)
})
```

**Module Mock:**
```javascript
// __mocks__/api.ts
import { vi } from 'vitest'

export const fetchUser = vi.fn()
export const createUser = vi.fn()

// In test
vi.mock('./api')
import { fetchUser } from './api'

test('fetches user', async () => {
  fetchUser.mockResolvedValue({ id: 1, name: 'John' })

  const user = await fetchUser(1)

  expect(user.name).toBe('John')
})
```

**Spy on Method:**
```javascript
import { vi } from 'vitest'

const obj = {
  method: () => 'original'
}

vi.spyOn(obj, 'method').mockReturnValue('mocked')

expect(obj.method()).toBe('mocked')
```

### TypeScript Mocks

**Type-Safe Mock:**
```typescript
import { vi } from 'vitest'

interface User {
  id: number
  name: string
  email: string
}

// Create type-safe mock
const mockUser: User = {
  id: 1,
  name: 'John Doe',
  email: '[email protected]'
}

// Mock function with types
const mockFetchUser = vi.fn<[id: number], Promise<User>>()
mockFetchUser.mockResolvedValue(mockUser)
```

**Mock Factory:**
```typescript
// Create a factory for generating mocks
function createMockUser(overrides?: Partial<User>): User {
  return {
    id: 1,
    name: 'Test User',
    email: '[email protected]',
    ...overrides
  }
}

// Use in tests
const user1 = createMockUser({ name: 'Alice' })
const user2 = createMockUser({ id: 2, email: '[email protected]' })
```

## Python Mocks

### unittest.mock

**Function Mock:**
```python
from unittest.mock import Mock

# Simple mock
mock_func = Mock(return_value=42)
assert mock_func() == 42
assert mock_func.called

# Mock with side effects
mock_func = Mock(side_effect=[1, 2, 3])
assert mock_func() == 1
assert mock_func() == 2
assert mock_func() == 3
```

**Patch Decorator:**
```python
from unittest.mock import patch, Mock

@patch('requests.get')
def test_fetch_data(mock_get):
    # Setup mock
    mock_response = Mock()
    mock_response.json.return_value = {'name': 'John'}
    mock_response.status_code = 200
    mock_get.return_value = mock_response

    # Test
    result = fetch_user_data(1)

    assert result['name'] == 'John'
    mock_get.assert_called_once_with('https://api.example.com/users/1')
```

**Class Mock:**
```python
from unittest.mock import Mock, patch

@patch('database.Database')
def test_database_query(mock_database_class):
    # Setup mock instance
    mock_db = Mock()
    mock_db.query.return_value = [{'id': 1, 'name': 'John'}]
    mock_database_class.return_value = mock_db

    # Test
    db = Database()
    users = db.query('SELECT * FROM users')

    assert len(users) == 1
    assert users[0]['name'] == 'John'
    mock_db.query.assert_called_once()
```

**Context Manager Mock:**
```python
from unittest.mock import patch, mock_open

# Mock file operations
mock_data = "file contents"
with patch('builtins.open', mock_open(read_data=mock_data)):
    with open('file.txt') as f:
        content = f.read()
    assert content == mock_data
```

### pytest Fixtures

**Simple Fixture:**
```python
import pytest

@pytest.fixture
def mock_user():
    return {
        'id': 1,
        'name': 'John Doe',
        'email': '[email protected]'
    }

def test_user_data(mock_user):
    assert mock_user['name'] == 'John Doe'
```

**Fixture with Cleanup:**
```python
@pytest.fixture
def mock_database():
    # Setup
    db = MockDatabase()
    db.connect()

    yield db  # Provide to test

    # Teardown
    db.disconnect()

def test_database_query(mock_database):
    result = mock_database.query('SELECT * FROM users')
    assert len(result) > 0
```

**Parametrized Fixture:**
```python
@pytest.fixture(params=[
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 30},
    {'name': 'Charlie', 'age': 35}
])
def mock_user(request):
    return request.param

def test_user_age(mock_user):
    assert mock_user['age'] > 0
```

### pytest-mock

```python
def test_api_call(mocker):
    # Mock a function
    mock_get = mocker.patch('requests.get')
    mock_get.return_value.json.return_value = {'status': 'ok'}

    result = fetch_data()

    assert result['status'] == 'ok'
    mock_get.assert_called_once()
```

## API Response Mocks

### REST API Mock

```javascript
// Mock fetch API
global.fetch = jest.fn(() =>
  Promise.resolve({
    ok: true,
    status: 200,
    json: async () => ({
      id: 1,
      name: 'John Doe',
      email: '[email protected]'
    }),
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  })
)

test('fetches user', async () => {
  const user = await fetchUser(1)

  expect(user.name).toBe('John Doe')
  expect(fetch).toHaveBeenCalledWith('/api

Related in Backend & APIs