AgentSkillsCN

vitest-testing

Oh My Brand!主题中,使用Vitest进行TypeScript/JavaScript的单元测试。包括测试环境搭建、Web组件测试、模拟模式以及测试覆盖率。在为前端代码编写单元测试时,请使用本指南。

SKILL.md
--- frontmatter
name: vitest-testing
description: Vitest unit testing for TypeScript/JavaScript in Oh My Brand! theme. Test setup, Web Component testing, mocking patterns, and coverage. Use when writing unit tests for frontend code.
metadata:
  author: Wesley Smits
  version: "1.0.0"

Vitest Testing

Unit testing TypeScript/JavaScript code with Vitest for the Oh My Brand! WordPress FSE theme.


When to Use

  • Writing unit tests for Web Components
  • Testing utility functions (debounce, throttle, etc.)
  • Mocking browser APIs (IntersectionObserver, matchMedia)
  • Achieving code coverage requirements

Configuration

FileTemplatePurpose
vitest.config.tsVitest configurationTest settings and coverage
setup.tsTest setupBrowser API mocks

Test Templates

TemplatePurpose
web-component.test.tsWeb Component tests
debounce.test.tsUtility function tests
mocking-patterns.tsMocking examples

Test Structure

typescript
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';

describe('ComponentName', () => {
    let element: HTMLElement;

    beforeEach(() => {
        document.body.innerHTML = `<my-component></my-component>`;
        element = document.querySelector('my-component')!;
    });

    afterEach(() => {
        document.body.innerHTML = '';
    });

    it('should initialize correctly', () => {
        expect(element).toBeDefined();
    });
});

Mock Patterns Quick Reference

Mock Functions

typescript
const mockFn = vi.fn();
mockFn.mockReturnValue('value');
mockFn.mockResolvedValue({ data: [] });
expect(mockFn).toHaveBeenCalledWith('arg');

Mock Timers

typescript
vi.useFakeTimers();
vi.advanceTimersByTime(100);
vi.useRealTimers();

Spy on Methods

typescript
const spy = vi.spyOn(object, 'method');
spy.mockReturnValue('mocked');
expect(spy).toHaveBeenCalled();

See mocking-patterns.ts for complete examples.


Coverage

Thresholds

MetricThreshold
Statements80%
Branches80%
Functions80%
Lines80%

What to Test

Always test:

  • Public methods and functions
  • Edge cases (empty arrays, null values)
  • Error handling paths
  • User interactions
  • Attribute change callbacks

Don't test:

  • Third-party library internals
  • Private implementation details
  • Simple getters/setters

Running Tests

CommandPurpose
pnpm testRun all tests
pnpm run test:watchWatch mode
pnpm run test:coverageWith coverage
pnpm test -- --testNamePattern="nav"Filter by name
pnpm test src/blocks/gallery/Specific directory

Related Skills


References