用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/ForceInjection/domain-driven-design-skills --skill mocking-strategies命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
Conduct deep academic research for philosophy, neuroscience, cognitive science, and theoretical computer science (computability, complexity, AI theory, logic). Use when user asks to: research academic topics, find scholarly papers, conduct literature reviews, analyze citations, synthesize research findings, explore philosophical arguments, investigate consciousness/cognition, study computability/decidability/Turing machines, or analyze academic debates. Triggers on: 'research papers', 'literature review', 'academic sources', 'scholarly articles', 'philosophy of mind', 'computability theory', 'neuroscience studies', 'find papers on', 'what does the research say'.
Create clear action plans with steps, success criteria, and risk awareness. Use before implementing features, making changes, starting projects, or anytime you need a roadmap to success. Triggers on "plan this", "how should we approach", "what's the strategy", "steps to complete", or when facing complex multi-step work.
Add keyboard navigation to a feature using CommandRegistryService. Use when implementing keyboard shortcuts, vim-style navigation, or hotkeys for a page or component.
基于 SOC 职业分类
正在显示 SKILL.md
| name | mocking-strategies |
| description | Test mocking strategies with Vitest. Use when mocking dependencies in tests. |
This skill covers mocking strategies for Vitest testing.
Use this skill when:
MOCK BOUNDARIES, NOT INTERNALS - Mock external dependencies (APIs, databases) not internal implementation.
import { vi, describe, it, expect } from 'vitest';
const mockFn = vi.fn();
// Call the mock
mockFn('arg1', 'arg2');
// Assertions
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2');
expect(mockFn).toHaveBeenCalledTimes(1);
const mockFn = vi.fn();
// Return specific value
mockFn.mockReturnValue('result');
// Return different values on subsequent calls
mockFn
.mockReturnValueOnce('first')
.mockReturnValueOnce('second')
.mockReturnValue('default');
// Return resolved promise
mockFn.mockResolvedValue({ data: 'value' });
// Return rejected promise
mockFn.mockRejectedValue(new Error('Failed'));
const mockFn = vi.fn().mockImplementation((a: number, b: number) => a + b);
expect(mockFn(1, 2)).toBe(3);
// One-time implementation
mockFn.mockImplementationOnce(() => 'special');
import { vi, describe, it, expect, afterEach } from 'vitest';
const calculator = {
add(a: number, b: number): number {
return a + b;
},
};
describe('calculator', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('should spy on add method', () => {
const spy = vi.spyOn(calculator, 'add');
calculator.add(1, 2);
expect(spy).toHaveBeenCalledWith(1, 2);
expect(spy).toHaveReturnedWith(3);
});
it('should mock return value', () => {
vi.spyOn(calculator, 'add').mockReturnValue(100);
expect(calculator.add(1, 2)).toBe(100);
});
});
class UserService {
async getUser(id: string): Promise<User> {
// Real implementation
}
}
it('should spy on class method', async () => {
const service = new UserService();
const spy = vi.spyOn(service, 'getUser').mockResolvedValue({
id: '123',
name: 'Test User',
});
const user = await service.getUser('123');
expect(spy).toHaveBeenCalledWith('123');
expect(user.name).toBe('Test User');
});
import { vi, describe, it, expect } from 'vitest';
import { fetchUser } from './api';
// Mock entire module
vi.mock('./api');
describe('with mocked api', () => {
it('should use mocked function', async () => {
// fetchUser is now a mock
vi.mocked(fetchUser).mockResolvedValue({ id: '1', name: 'Mock User' });
const user = await fetchUser('1');
expect(user.name).toBe('Mock User');
});
});
vi.mock('./api', () => ({
fetchUser: vi.fn().mockResolvedValue({ id: '1', name: 'Mock User' }),
fetchPosts: vi.fn().mockResolvedValue([]),
}));
vi.mock('./utils', async (importOriginal) => {
const actual = await importOriginal<typeof import('./utils')>();
return {
...actual,
// Only mock specific exports
formatDate: vi.fn().mockReturnValue('mocked date'),
};
});
import { vi } from 'vitest';
import fs from 'node:fs';
vi.mock('node:fs');
it('should mock fs.readFile', async () => {
vi.mocked(fs.readFile).mockImplementation((path, callback) => {
callback(null, 'mocked content');
});
});
vi.mock('axios', () => ({
default: {
get: vi.fn().mockResolvedValue({ data: { id: 1 } }),
post: vi.fn().mockResolvedValue({ data: { success: true } }),
},
}));
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
describe('timer tests', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('should advance timers', () => {
const callback = vi.fn();
setTimeout(callback, 1000);
expect(callback).not.toHaveBeenCalled();
vi.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalled();
});
it('should run all timers', () => {
const callback = vi.fn();
setTimeout(callback, 1000);
setTimeout(callback, 2000);
vi.runAllTimers();
expect(callback).toHaveBeenCalledTimes(2);
});
});
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2024-01-01'));
});
afterEach(() => {
vi.useRealTimers();
});
it('should use mocked date', () => {
expect(new Date().toISOString()).toBe('2024-01-01T00:00:00.000Z');
});
const mockFn = vi.fn();
// Call count
expect(mockFn).toHaveBeenCalledTimes(3);
expect(mockFn).toHaveBeenCalledOnce();
// Call arguments
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2');
expect(mockFn).toHaveBeenLastCalledWith('last', 'args');
expect(mockFn).toHaveBeenNthCalledWith(2, 'second', 'call');
// Return values
expect(mockFn).toHaveReturned();
expect(mockFn).toHaveReturnedWith('value');
expect(mockFn).toHaveLastReturnedWith('last');
// Access call info
expect(mockFn.mock.calls[0]).toEqual(['first', 'call']);
expect(mockFn.mock.results[0].value).toBe('result');
const mockFn = vi.fn();
// Clear call history (keeps implementation)
mockFn.mockClear();
// or
vi.clearAllMocks();
// Reset to initial state (clears implementation)
mockFn.mockReset();
// or
vi.resetAllMocks();
// Restore original implementation (for spies)
mockFn.mockRestore();
// or
vi.restoreAllMocks();
const userRepository = {
findById: vi.fn().mockResolvedValue({ id: '1', name: 'Test' }),
};
const analytics = {
track: vi.fn(),
};
// Act
performAction();
// Assert calls were made
expect(analytics.track).toHaveBeenCalledWith('action', { type: 'click' });
class FakeUserRepository implements UserRepository {
private users = new Map<string, User>();
async save(user: User): Promise<void> {
this.users.set(user.id, user);
}
async findById(id: string): Promise<User | null> {
return this.users.get(id) ?? null;
}
}