Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

testing-unit检测单位

Agent Skill

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

总安装

1,285

周安装

53

GitHub Stars

160

下载量

420
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:testing-unit(检测单位)
来源仓库:https://github.com/yonatangross/orchestkit
仓库路径:skills/testing-unit
安装命令:
npx skills add https://github.com/yonatangross/orchestkit --skill testing-unit
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/yonatangross/orchestkit --skill testing-unit

简介

testing-unit 用于辅助测试设计、自动化测试、用例整理和回归验证。

  • 适合编写单元测试、端到端测试、测试计划或根据失败日志定位问题。
  • 使用时需确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器服务时应区分本地模拟与生产环境。
  • 建议在测试环境中验证后再部署到生产系统。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Unit Testing Patterns

Focused patterns for writing isolated, fast, maintainable unit tests. Covers test structure (AAA), parametrization, fixture management, HTTP mocking (MSW/VCR), and test data generation with factories.

Each category has individual rule files in rules/ loaded on-demand, plus reference material, checklists, and scaffolding scripts.

Core Principles (ALWAYS apply)

  1. AAA structure: Every test MUST follow Arrange-Act-Assert. Use // Arrange, // Act, // Assert comments for clarity.
  2. Parametrize, don't duplicate: Use test.each (TypeScript) or @pytest.mark.parametrize (Python) when testing multiple inputs. Never copy-paste the same test body with different values.
  3. Fixture scoping matters: Use scope="function" (default) for mutable data. Use scope="module" or scope="session" ONLY for expensive read-only resources (DB engines, ML models). Mutable data with shared scope causes flaky tests.
  4. Speed target: Each unit test should run under 100ms. If it's slower, you're likely hitting I/O — mock it.
  5. Mock at the network level: Use MSW (TypeScript) or VCR.py (Python) to intercept HTTP at the network layer. Never mock fetch/axios/requests directly.

Quick Reference

CategoryRulesImpactWhen to Use
Unit Test Structure3CRITICALWriting any unit test
HTTP Mocking2HIGHMocking API calls in frontend/backend tests
Test Data Management3MEDIUMSetting up test data, factories, fixtures

Total: 8 rules across 3 categories, 4 references, 3 checklists, 1 example set, 3 scripts

Unit Test Structure

Core patterns for structuring isolated unit tests with clear phases and efficient execution.

RuleFileKey Pattern
AAA Patternrules/unit-aaa-pattern.mdArrange-Act-Assert with isolation
Fixture Scopingrules/unit-fixture-scoping.mdfunction/module/session scope selection
Parametrized Testsrules/unit-parametrized.mdtest.each / @pytest.mark.parametrize

Reference: references/aaa-pattern.md — detailed AAA implementation with checklist

HTTP Mocking

Network-level request interception for deterministic tests without hitting real APIs.

RuleFileKey Pattern
MSW 2.xrules/mocking-msw.mdNetwork-level mocking for frontend (TypeScript)
VCR.pyrules/mocking-vcr.mdRecord/replay HTTP cassettes (Python)

References:

  • references/msw-2x-api.md — full MSW 2.x API (handlers, GraphQL, WebSocket, passthrough)
  • references/stateful-testing.md — Hypothesis RuleBasedStateMachine for stateful tests

Checklists:

  • checklists/msw-setup-checklist.md — MSW installation, handler setup, test writing
  • checklists/vcr-checklist.md — VCR configuration, sensitive data filtering, CI setup

Examples: examples/handler-patterns.md — CRUD, error simulation, auth flow, file upload handlers

Test Data Management

Factories, fixtures, and seeding patterns for isolated, realistic test data.

RuleFileKey Pattern
Data Factoriesrules/data-factories.mdFactoryBoy / @faker-js builders
Data Fixturesrules/data-fixtures.mdJSON fixtures with composition
Seeding & Cleanuprules/data-seeding-cleanup.mdAutomated DB seeding and teardown

Reference: references/factory-patterns.md — advanced factory patterns (Sequence, SubFactory, Traits)

Checklist: checklists/test-data-checklist.md — data generation, cleanup, isolation verification

Quick Start

TypeScript (Vitest + MSW)

import { describe, test, expect, beforeAll, afterEach, afterAll } from 'vitest';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { calculateDiscount } from './pricing';

// 1. Pure unit test with AAA pattern
describe('calculateDiscount', () => {
  test.each([
    [100, 0],
    [150, 15],
    [200, 20],
  ])('for order $%i returns $%i discount', (total, expected) => {
    // Arrange
    const order = { total };

    // Act
    const discount = calculateDiscount(order);

    // Assert
    expect(discount).toBe(expected);
  });
});

// 2. MSW mocked API test
const server = setupServer(
  http.get('/api/users/:id', ({ params }) => {
    return HttpResponse.json({ id: params.id, name: 'Test User' });
  })
);

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('fetches user from API', async () => {
  // Arrange — MSW handler set up above

  // Act
  const response = await fetch('/api/users/123');
  const data = await response.json();

  // Assert
  expect(data.name).toBe('Test User');
});

Python (pytest + FactoryBoy)

import pytest
from factory import Factory, Faker, SubFactory

class UserFactory(Factory):
    class Meta:
        model = dict
    email = Faker('email')
    name = Faker('name')

class TestUserService:
    @pytest.mark.parametrize("role,can_edit", [
        ("admin", True),
        ("viewer", False),
    ])
    def test_edit_permission(self, role, can_edit):
        # Arrange
        user = UserFactory(role=role)

        # Act
        result = user_can_edit(user)

        # Assert
        assert result == can_edit

Vitest 4.1 Features

aroundEach / aroundAll (preferred for DB transactions)

Wraps each test in setup/teardown — cleaner than separate beforeEach/afterEach for transactions:

test.aroundEach(async (runTest, { db }) => {
  await db.transaction(runTest)  // auto-rollback on test end
})

test('insert user', async ({ db }) => {
  await db.insert({ name: 'Alice' })
  // transaction auto-rolls back — no cleanup needed
})

aroundAll wraps entire suites the same way.

mockThrow / mockThrowOnce

Replaces the verbose mockImplementation(() => {throw err}) pattern:

const fn = vi.fn()
fn.mockThrow(new Error('connection lost'))  // always throws
fn.mockThrowOnce(new Error('timeout'))      // throws once, then normal

vi.defineHelper (clean stack traces)

Custom assertion helpers that point errors to the call site, not the helper internals:

const assertPair = vi.defineHelper((a, b) => {
  expect(a).toEqual(b)  // error points to where assertPair() was CALLED
})

Test Tags

Filter tests by tags in CLI — useful for CI fast paths:

// vitest.config.ts
test: {
  tags: {
    unit: { timeout: 5000 },
    flaky: { retry: 3 },
  }
}
vitest --tags-filter="unit and !flaky"
vitest --tags-filter="(unit or integration) and !slow"

Agent Reporter

Minimal output (failures only) — use in AI agent / CI contexts:

AI_AGENT=copilot vitest    # auto-detect agent mode

Key Decisions

DecisionRecommendation
Test framework (TS)Vitest 4.1+ (modern, fast, aroundEach, test tags) or Jest (mature ecosystem)
Test framework (Python)pytest with plugins (parametrize, asyncio, cov)
HTTP mocking (TS)MSW 2.x at network level, never mock fetch/axios directly
HTTP mocking (Python)VCR.py with cassettes, filter sensitive data
Test dataFactories (FactoryBoy/faker-js) over hardcoded fixtures
Fixture scopescope="function" for mutable (default). module/session ONLY for expensive immutable resources
Execution timeUnder 100ms per unit test — if slower, mock external calls
Coverage target90%+ business logic, 100% critical paths

Common Mistakes

  1. Testing implementation details instead of public behavior (brittle tests)
  2. Mocking fetch/axios directly instead of using MSW at network level (incomplete coverage)
  3. Shared mutable state between tests via module-scoped fixtures (flaky tests)
  4. Hard-coded test data with duplicate IDs (test conflicts in parallel runs)
  5. No cleanup after database seeding (state leaks between tests)
  6. Over-mocking — testing your mocks instead of your code (false confidence)
  7. Verbose throw mockingmockImplementation(() => {throw err}) instead of mockThrow(err) (Vitest 4.1+)

Scripts

ScriptFilePurpose
Create Test Casescripts/create-test-case.mdScaffold test file with auto-detected framework
Create Test Fixturescripts/create-test-fixture.mdScaffold pytest fixture with context detection
Create MSW Handlerscripts/create-msw-handler.mdScaffold MSW handler for an API endpoint

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.62%
按下载量换算150

Claude

30.84%
按下载量换算130

Cursor

19.86%
按下载量换算83

Gemini CLI

9.67%
按下载量换算41

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills