Test mocking strategies with Vitest. Use when mocking dependencies in tests.
Provides Vitest mocking strategies for testing with vi.fn(), vi.spyOn(), and vi.mock().
npx claudepluginhub 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;
}
}
Activates when the user asks about AI prompts, needs prompt templates, wants to search for prompts, or mentions prompts.chat. Use for discovering, retrieving, and improving prompts.
Search, retrieve, and install Agent Skills from the prompts.chat registry using MCP tools. Use when the user asks to find skills, browse skill catalogs, install a skill for Claude, or extend Claude's capabilities with reusable AI agent components.
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems. Create original algorithmic art rather than copying existing artists' work to avoid copyright violations.