vitest-skill: Enabling AI Assistants to Write Unit and Integration Tests Following Vitest Conventions

Preface

In the Vite ecosystem, Vitest has become a common choice for unit testing: sharing configuration and the transformation pipeline with Vite, startup and watch are typically lighter than traditional Jest pipelines. When teams migrate from Jest, the most common pitfalls are the mock namespace (jest.* vs vi.*), vi.mock hoisting under ESM, and how to configure fields like environment and globals in vitest.config.ts.

If these conventions are left for AI to “guess” on the fly, issues like jest.fn(), missing import { vi } from 'vitest', or configuration inconsistent with the actual project directory often arise. vitest-skill is an Agent Skill maintained by TestMu AI (formerly LambdaTest) in the agent-skills repository. It is designed for coding assistants like Cursor, Claude Code, GitHub Copilot, and Gemini CLI. When users mention keywords such as Vitest, vi.mock, or vitest.config, it guides the generation of JavaScript/TypeScript test code that aligns with Vitest conventions.

What is This

The positioning of vitest-skill is to generate Vitest unit tests and related integration testing patterns within AI conversations, emphasizing Jest-compatible APIs, ESM support, and a test execution mode originating from Vite. The Skill metadata lists the author as TestMu AI, version 1.0, MIT license, applicable languages as JavaScript and TypeScript, and the category as unit-testing.

Official Skill Directory: https://github.com/LambdaTest/agent-skills/tree/main/vitest-skill

Trigger scenarios (from the Skill description) include users mentioning “Vitest”, “vi.mock”, “vitest.config”, “vi.fn”, “Vite test”, “vitest config”, etc.

Compared to Skills for Jest, Cypress, etc. in the same repository, vitest-skill focuses on the vi namespace within Vite projects, In-Source Testing, and component testing patterns combined with @testing-library/react, rather than browser E2E or the pure Jest default stack.

Core Features

The following content is derived from the official Skill documentation and Quick Reference; capabilities not present in the materials are not expanded upon.

Basic Test Structure

The Skill embeds typical patterns like describe, it, expect, and beforeEach, explicitly imported from the vitest package, as shown below.

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Calculator } from './calculator';

describe('Calculator', () => {
  let calc: Calculator;
  beforeEach(() => { calc = new Calculator(); });

  it('adds two numbers', () => {
    expect(calc.add(2, 3)).toBe(5);
  });

  it('throws on divide by zero', () => {
    expect(() => calc.divide(10, 0)).toThrow();
  });
});

Mock, Spy, and Timers (vi instead of jest)

The materials explicitly require the use of vi.mock, vi.fn, vi.spyOn, and fake timers APIs, and point out in the Anti-Patterns table that jest.fn() / jest.mock() should not be used.

import { vi } from 'vitest';

vi.mock('./database', () => ({
  getUser: vi.fn().mockResolvedValue({ name: 'Alice' }),
  saveUser: vi.fn().mockResolvedValue(true),
}));

const mockFn = vi.fn();
mockFn.mockReturnValue(42);
mockFn.mockResolvedValue({ data: 'test' });

const spy = vi.spyOn(console, 'log').mockImplementation(() => {});
expect(spy).toHaveBeenCalledWith('message');
spy.mockRestore();

vi.useFakeTimers();
vi.advanceTimersByTime(1000);
vi.runAllTimers();
vi.useRealTimers();

In-Source Testing

Supports writing inline tests within business source code via import.meta.vitest; this requires configuring includeSource in vitest.config (see configuration example below).

Snapshot

Includes examples of toMatchSnapshot and toMatchInlineSnapshot.

React Component Testing

Examples combine render and screen from @testing-library/react, importing describe / it / expect from vitest in the test file.

Anti-Patterns Comparison

Not Recommended Recommended Description
jest.fn() vi.fn() Vitest uses the vi namespace
jest.mock() vi.mock() Different from the Jest namespace
No type constraints TypeScript + strict The Skill emphasizes TS priority

Command Quick Reference

Task Command
Single run npx vitest run
Watch (default) npx vitest
UI npx vitest --ui
Coverage npx vitest --coverage
Specific file npx vitest run src/math.test.ts
Filter by test name npx vitest run -t "adds"

The production-oriented configuration example provided in the Skill documentation includes globals, jsdom environment, v8 coverage, and includeSource:

import { defineConfig } from 'vitest/config';
export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
    coverage: { provider: 'v8', reporter: ['text', 'html'] },
    include: ['src/**/*.{test,spec}.{js,ts,tsx}'],
    includeSource: ['src/**/*.{js,ts}'],
  },
});

In-Depth Reference Playbook

Longer patterns (workspace configuration, React Testing Library, table-driven test.each, API/integration testing, GitHub Actions CI, debugging checklists, etc.) are located in reference/playbook.md within the Skill repository, comprising 10 chapters; if you need the AI to expand on a specific scenario, you can name the topic from the playbook in your conversation.

Installation and Activation

vitest-skill is released with LambdaTest/agent-skills. The repository README states: Node.js and npm are required (latest stable version recommended), a working AI coding assistant is needed, and a TestMu AI account username and access key are required (used for agentskillsforall related workflows).

Repository-level Initialization (Optional)

If you already have a local clone of agent-skills, you can first install CLI dependencies and register the skill source:

git clone https://github.com/LambdaTest/agent-skills && cd agent-skills
npx agentskillsforall add https://github.com/LambdaTest/agent-skills.git

Credential environment variables (macOS / Linux):

export LT_USERNAME="YOUR_USERNAME"
export LT_ACCESS_KEY="YOUR_ACCESS_KEY"

Windows uses set LT_USERNAME=... and set LT_ACCESS_KEY=... (refer to official documentation for specifics).

Install Only vitest-skill

npx agentskillsforall add https://github.com/LambdaTest/agent-skills.git --skill vitest-skill

View all Skills under this source:

npx agentskillsforall list https://github.com/LambdaTest/agent-skills.git

The specific “skill mount paths” for assistants like Cursor, Claude Code, and Copilot vary by product version; see the TestMu AI Agent Skills documentation for complete steps. Once installed, describe your testing needs in natural language within the project, for example, requesting to supplement Vitest cases for a module with vi.mock.

Typical Usage

Below are several usage examples consistent with the official samples that can be directly verified against the repository.

1. Write Basic Cases for Pure Functions or Classes

Describe the module path under test and boundary conditions (exceptions, division by zero, etc.), and explicitly require using vitest imports instead of jest. Under Skill constraints, the assistant should output a file with the same structure as the Calculator example above.

2. Write Mocks for Code Depending on External Modules

Provide the path of the module to be mocked and the expected return values in the conversation, and mention vi.mock or vi.fn. The database mock and spy snippets in the Skill materials serve as expected forms.

3. React Components

Describe the component props and the text that should appear in the DOM, requiring the use of @testing-library/react + Vitest. The official example asserts via screen.getByText.

4. Linking with Configuration

If the project uses In-Source Testing, explain the includeSource in vitest.config.ts and the import.meta.vitest conditional block together, to avoid generating test logic without the necessary configuration.

5. Local Execution Verification

After generating code, use the commands from the Skill Quick Reference to verify locally, for example:

npx vitest run
npx vitest run -t "adds"

Applicable Scenarios and Notes

Suitable for:

  • Frontend or full-stack TypeScript projects using the Vite / Vitest stack that need AI to generate or complete *.test.ts / *.spec.tsx.
  • Teams migrating from Jest who want to unify output to the vi.* API.
  • Acting as a “standard anchor” in conversations when mock modules, fake timers, snapshots, or RTL component testing templates are needed.

Notes:

  • The Skill guides test code and configuration patterns; it does not replace installing dependencies like vitest, @vitejs/plugin-*, jsdom, etc. on your local machine; versions must match the project package.json, and the materials do not bind specific Vitest version numbers.
  • The Anti-Patterns table only covers the most common jest namespace misuses; if third-party libraries still expose Jest globals, they need to be handled separately at the project level.
  • CI, integration testing, etc. in reference/playbook.md are for extended reading; generated results should still undergo npx vitest run and code review.
  • TestMu AI cloud platform and Tunnel capabilities belong to the overall capabilities of the agent-skills repository; vitest-skill itself focuses on local Vitest code generation; whether to execute on the cloud depends on other Skills or your own CI.

Conclusion

vitest-skill consolidates Vitest’s import methods, vi mocks, configuration fields, and common CLI into reusable instructions for Agents, reducing the probability of AI writing Jest-style code in Vite projects. If you are already using Vitest or configuring vitest.config, you can select this Skill in comparison with Skills for Jest, Cypress, etc. in the repository.

Official Address: https://github.com/LambdaTest/agent-skills/tree/main/vitest-skill

羽毛球分组比赛记分
小程序二维码

欢迎使用《羽毛球分组比赛记分》微信小程序

Xiaoye