writing-unit-tests-typescript
БесплатноБез исполняемых скриптовНе проверенGuidelines and patterns for writing unit tests in TypeScript using Vitest.
от microsoft-foundry★ 137 звёзд на GitHubОб этом скилле
Skill: Writing TypeScript Unit Tests
Overview
This skill covers writing unit tests for the frontend using Vitest.
Project Structure
frontend/
├── package.json # vitest + jsdom devDependencies
├── vite.config.ts # Vitest config inline
└── src/
├── config/
│ └── __tests__/
│ └── authConfig.test.ts
├── utils/
│ ├── citationParser.ts
│ ├── sseParser.ts
│ ├── fileAttachments.ts
│ └── __tests__/
│ ├── citationParser.test.ts
│ ├── sseParser.test.ts
│ └── fileAttachments.test.ts
├── services/
│ └── __tests__/
│ └── chatService.test.ts
└── reducers/
├── appReducer.ts
└── __tests__/
└── appReducer.test.ts # Includes state shape snapshot
Configuration
The Vitest config lives inline in vite.config.ts:
export default defineConfig({
// ... existing config
test: {
globals: true,
environment: "jsdom",
include: ["src/**/*.test.{ts,tsx}"],
},
});
Test Anatomy
import { describe, it, expect } from "vitest";
import { parseCitations, deduplicateAnnotations } from "../citationParser";
describe("citationParser", () => {
describe("parseCitations", () => {
it("returns empty array for empty input", () => {
expect(parseCitations("", [])).toEqual([]);
});
it("extracts citation markers from text", () => {
const text = "Hello [1] world [2]";
const result = parseCitations(text, annotations);
expect(result).toHaveLength(2);
});
});
describe("deduplicateAnnotations", () => {
it("removes duplicate annotations by URL", () => {
const annotations = [
{ url: "https://example.com", title: "Example" },
{ url: "https://example.com", title: "Example Duplicate" },
];
expect(deduplicateAnnotations(annotations)).toHaveLength(1);
});
});
});
Running Tests
# Run tests in watch mode (interactive)
cd frontend
npm test
# Run tests once (CI mode)
npm run test:run
# Run with coverage
npm run test:coverage
# Run specific file
npx vitest run src/utils/__tests__/citationParser.test.ts
# Run tests matching pattern
npx vitest run --testNamePattern="parseCitations"
Testable Units in This Project
Utils (Pure Functions - Easy to Test)
| File | Functions to Test |
|---|---|
citationParser.ts |
parseContentWithCitations |
sseParser.ts |
parseSseLine, splitSseBuffer |
fileAttachments.ts |
validateFile, validateImageFile, validateDocumentFile, validateFileCount, getEffectiveMimeType, convertFilesToDataUris |
errorHandler.ts |
getUserFriendlyMessage, createAppError, getErrorCodeFromResponse, parseErrorFromResponse, getErrorCodeFromMessage, isTokenExpiredError, isNetworkError, retryWithBackoff |
Reducers (Pure Functions - Easy to Test)
| File | What to Test |
|---|---|
appReducer.ts |
All action types, state transitions, immutability |
Components (Require React Testing Library)
For component testing, add @testing-library/react only when needed:
import { render, screen } from "@testing-library/react";
import { ChatMessage } from "../ChatMessage";
it("renders message content", () => {
render(<ChatMessage role="user" content="Hello" />);
expect(screen.getByText("Hello")).toBeInTheDocument();
});
Assertions Reference
Vitest uses Chai-style assertions via expect:
// Equality
expect(actual).toBe(expected); // strict equality (===)
expect(actual).toEqual(expected); // deep equality
// Truthiness
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeUndefined();
// Numbers
expect(num).toBeGreaterThan(5);
expect(num).toBeLessThanOrEqual(10);
// Strings
expect(str).toContain("substring");
expect(str).toMatch(/regex/);
// Arrays
expect(arr).toHaveLength(3);
expect(arr).toContain(item);
// Objects
expect(obj).toHaveProperty("key");
expect(obj).toMatchObject({ partial: "match" });
// Exceptions
expect(() => throwingFn()).toThrow();
expect(() => throwingFn()).toThrowError("message");
// Async
await expect(asyncFn()).resolves.toBe(value);
await expect(asyncFn()).rejects.toThrow();
Test Organization
Use describe blocks to group related tests:
describe("moduleName", () => {
describe("functionName", () => {
it("handles normal case", () => {});
it("handles edge case", () => {});
it("throws on invalid input", () => {});
});
});
State Shape Snapshot Tests
Use state shape snapshots to prevent accidental state changes from going unnoticed. If a new field is added to AppState without updating the test, it fails:
it('should have expected state shape (update this test when adding new state fields)', () => {
const shape = JSON.stringify(Object.keys(ini
Установить writing-unit-tests-typescript в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл writing-unit-tests-typescript?
Guidelines and patterns for writing unit tests in TypeScript using Vitest.
Как установить скилл writing-unit-tests-typescript?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл writing-unit-tests-typescript запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic