Vitest Migration & Config
БесплатноБез исполняемых скриптовНе проверенTeaches the agent to migrate a Jest suite to Vitest — vi.mock and the globals shim, vitest.config workspaces/projects, coverage, browser mode, and Vitest v4…
от PramodDutta★ 253 звезды на GitHubОб этом скилле
Vitest Migration & Config
This skill makes the agent migrate a Jest test suite to Vitest correctly and configure Vitest from scratch. Vitest is mostly Jest-compatible, but the differences bite: the vi namespace replaces jest, vi.mock hoisting needs vi.hoisted, ESM is first-class, and Vitest v4 removed workspace files in favor of inline projects. The agent should produce a config that runs fast, types cleanly, and reports coverage.
Use this skill when migrating from Jest, setting up vitest.config.ts, splitting unit vs browser tests, or resolving v4 upgrade breakage.
Core Principles
vireplacesjest.jest.fn->vi.fn,jest.mock->vi.mock,jest.spyOn->vi.spyOn,jest.useFakeTimers->vi.useFakeTimers. The assertion API (expect, matchers) is unchanged.- Mocks must reset explicitly. Set
test.clearMocks/restoreMocksin config or callvi.clearAllMocks()inbeforeEach— Vitest does not reset by default. vi.mockis hoisted; usevi.hoistedfor shared values. Variables the factory needs must be created viavi.hoisted(() => ...), since the factory runs before imports.- Decide on globals up front. Either enable
globals: true(Jest-like, no imports) or import{ describe, it, expect, vi }fromvitest. Pick one and addtypes: ['vitest/globals']if using globals. - v4 uses
projects, notworkspace. The standalonevitest.workspace.tsfile is removed; declare multiple environments via the inlineprojectsarray. - Browser mode replaces jsdom for real-DOM tests. Use
browser.instances(v4) to run component tests in a real browser engine via Playwright.
Workflow / Patterns
Pattern 1 — Mechanical Jest -> Vitest swap
Most test bodies migrate with a namespace rename. With globals: true, even the imports can stay as-is.
// Before (Jest):
// const fn = jest.fn();
// jest.spyOn(obj, 'method');
// jest.useFakeTimers();
// After (Vitest) — explicit imports (recommended, ESM-safe):
import { describe, it, expect, vi, beforeEach } from 'vitest';
describe('cart', () => {
beforeEach(() => vi.clearAllMocks());
it('adds an item', () => {
const onChange = vi.fn();
const cart = createCart(onChange);
cart.add({ sku: 'A1', qty: 2 });
expect(cart.total).toBe(2);
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ sku: 'A1' }));
});
});
Pattern 2 — vi.mock with vi.hoisted (the hoisting fix)
In Jest you prefix variables with mock. In Vitest, wrap them in vi.hoisted so they exist when the hoisted factory runs.
import { vi, test, expect, beforeEach } from 'vitest';
import { getUser } from './user-service';
import axios from 'axios';
// Create the spy in a hoisted block so the factory below can reference it.
const { mockGet } = vi.hoisted(() => ({ mockGet: vi.fn() }));
vi.mock('axios', () => ({
default: { get: mockGet }, // note: ESM default export shape
}));
beforeEach(() => vi.clearAllMocks());
test('resolves user from API', async () => {
mockGet.mockResolvedValue({ data: { id: 1, name: 'Ada' } });
const user = await getUser(1);
expect(user).toEqual({ id: 1, name: 'Ada' });
expect(axios.get).toHaveBeenCalledWith('/api/users/1');
});
Pattern 3 — Partial mock with importActual
The Vitest equivalent of jest.requireActual. The factory is async.
vi.mock('./config', async (importOriginal) => {
const actual = await importOriginal<typeof import('./config')>();
return {
...actual,
isProduction: vi.fn(() => false), // override one export, keep the rest real
};
});
Pattern 4 — A complete vitest.config.ts
Covers globals, environment, setup files, and coverage. This replaces jest.config.js.
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true, // Jest-like; otherwise import from 'vitest'
environment: 'node', // 'jsdom' for component DOM tests
setupFiles: ['./test/setup.ts'],
clearMocks: true, // reset vi.fn() call data before each test
restoreMocks: true, // restore spies to original impl
coverage: {
provider: 'v8', // fast, no instrumentation step
reporter: ['text', 'html', 'lcov'],
include: ['src/**/*.ts'],
exclude: ['src/**/*.d.ts', 'src/**/index.ts'],
thresholds: { lines: 80, functions: 80, branches: 75 },
},
},
});
If using globals: true, add to tsconfig.json:
{ "compilerOptions": { "types": ["vitest/globals"] } }
Pattern 5 — Multiple environments via projects (v4)
The v4 replacement for vitest.workspace.ts. Run Node unit tests and jsdom component tests in one command, each with its own config.
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
coverage: { provider: 'v8' },
projects: [
{
// Fast pure-logic tests in Node.
test: {
Установить Vitest Migration & Config в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Vitest Migration & Config?
Teaches the agent to migrate a Jest suite to Vitest — vi.mock and the globals shim, vitest.config workspaces/projects, coverage, browser mode, and Vitest v4 breaking changes.
Как установить скилл Vitest Migration & Config?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Vitest Migration & Config запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic