Test mocking strategies with Vitest. Use when mocking dependencies in tests.
/plugin marketplace add IvanTorresEdge/molcajete.ai/plugin install ivantorresedge-js-tech-stacks-js-common@IvanTorresEdge/molcajete.aiThis skill inherits all available tools. When active, it can use any tool Claude has access to.
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;
}
}
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.