mock-generator
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".
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('/apiRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.