Token导航 LogoToken导航

Agent Skill · 研究检索

typescript-unit-testing(TypeScript unit 测试)

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

typescript-unit-testing 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为只读;许可证信息还不明确,第三方扫描有未通过项,按安装量在研究检索类的 73,675 个 Skill 里排第 18,474。

总安装 6,068周安装 258GitHub Stars 8下载 2,126核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/bmad-labs/skills --skill typescript-unit-testing

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

辅助测试设计与自动化验证,支持单元测试用例编写与回归检查。可用于根据失败日志定位问题或制定测试策略。需确认项目测试框架和运行命令后再使用。涉及外部服务时应区分本地模拟与真实环境。typescript-unit-testing 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/typescript-unit-testing

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/bmad-labs/skills --skill typescript-unit-testi…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它标注为只读,先用只读任务试一次,确认行为符合预期再扩大使用范围。

常见问题

6 条

typescript-unit-testing 怎么安装?

在终端执行 npx skills add https://github.com/bmad-labs/skills --skill typescript-unit-testing。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

typescript-unit-testing 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

typescript-unit-testing 需要什么权限?

权限级别是只读。该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

typescript-unit-testing 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

typescript-unit-testing 用的人多吗?

公开数据是累计安装 6,068 次,近一周安装 258 次,下载 2,126 次,GitHub 8 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

typescript-unit-testing 安全吗?

第三方扫描有未通过项,风险较高。除非你确认过源码,否则不建议直接安装到常用环境。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 标注为只读权限,试用阶段不容易误改本地文件。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。
  • 只想先试试效果、不希望它改动本地文件的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
typescript-unit-testing

TypeScript unit 测试 · 本页

6,0688只读未明确未通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Unit Testing Skill

Unit testing validates individual functions, methods, and classes in isolation by mocking all external dependencies.


Workflows

For guided, step-by-step execution of unit testing tasks, use the appropriate workflow:

WorkflowPurposeWhen to Use
SetupInitialize test infrastructureNew project or missing test setup
WritingWrite new unit testsCreating tests for components
ReviewingReview existing testsCode review, quality audit
RunningExecute testsRunning tests, analyzing results
DebuggingFix failing testsTests failing, need diagnosis
OptimizingImprove test performanceSlow tests, maintainability

Workflow Selection Guide

IMPORTANT: Before starting any testing task, identify the user's intent and load the appropriate workflow.

Detect User Intent → Select Workflow

User Says / WantsWorkflow to LoadFile
"Set up tests", "configure Jest", "add testing to project", "install test dependencies"Setupworkflows/setup/workflow.md
"Write tests", "add tests", "create tests", "test this service/controller"Writingworkflows/writing/workflow.md
"Review tests", "check test quality", "audit tests", "are these tests good?"Reviewingworkflows/reviewing/workflow.md
"Run tests", "execute tests", "check if tests pass", "show test results"Runningworkflows/running/workflow.md
"Fix tests", "debug tests", "tests are failing", "why is this test broken?"Debuggingworkflows/debugging/workflow.md
"Speed up tests", "optimize tests", "tests are slow", "fix open handles"Optimizingworkflows/optimizing/workflow.md

Workflow Execution Protocol

  1. ALWAYS load the workflow file first - Read the full workflow before taking action
  2. Follow each step in order - Complete checkpoints before proceeding
  3. Load knowledge files as directed - Each workflow specifies which references/ files to read
  4. Verify compliance after completion - Re-read relevant reference files to ensure quality

Knowledge Base Structure

references/
├── common/              # Core testing fundamentals
│   ├── knowledge.md     # Testing philosophy and test pyramid
│   ├── rules.md         # Mandatory testing rules (AAA, naming, coverage)
│   ├── assertions.md    # Assertion patterns and matchers
│   ├── examples.md      # Comprehensive examples by category
│   ├── detect-open-handles.md   # Open handle detection and cleanup
│   └── performance-optimization.md  # Jest runtime optimization
│
├── nestjs/              # NestJS component testing
│   ├── services.md      # Service/usecase testing patterns
│   ├── controllers.md   # Controller testing patterns
│   ├── guards.md        # Guard testing patterns
│   ├── interceptors.md  # Interceptor testing patterns
│   └── pipes-filters.md # Pipe and filter testing
│
├── mocking/             # Mock patterns and strategies
│   ├── deep-mocked.md   # @golevelup/ts-jest patterns
│   ├── jest-native.md   # Jest.fn, spyOn, mock patterns
│   └── factories.md     # Test data factory patterns
│
├── repository/          # Repository testing
│   ├── mongodb.md       # mongodb-memory-server patterns
│   └── postgres.md      # pg-mem patterns
│
├── kafka/               # NestJS Kafka microservices testing
│   └── kafka.md         # ClientKafka, @MessagePattern, @EventPattern handlers
│
└── redis/               # Redis cache testing
    └── redis.md         # Cache operations, health checks, graceful degradation

Quick Reference by Task

Write Unit Tests

  1. MANDATORY: Read references/common/rules.md - AAA pattern, naming, coverage
  2. Read references/common/assertions.md - Assertion best practices
  3. Read component-specific files:

- Services: references/nestjs/services.md - Controllers: references/nestjs/controllers.md - Guards: references/nestjs/guards.md - Interceptors: references/nestjs/interceptors.md - Pipes/Filters: references/nestjs/pipes-filters.md

Setup Mocking

  1. Read references/mocking/deep-mocked.md - DeepMocked patterns
  2. Read references/mocking/jest-native.md - Native Jest patterns
  3. Read references/mocking/factories.md - Test data factories

Test Repositories

  1. MongoDB: references/repository/mongodb.md
  2. PostgreSQL: references/repository/postgres.md

Test Kafka (NestJS Microservices)

  • Read references/kafka/kafka.md - ClientKafka mocking, @MessagePattern/@EventPattern handlers, emit/send testing

Test Redis

  • Read references/redis/redis.md - Cache operations, health checks, graceful degradation

Examples

  • Read references/common/examples.md for comprehensive patterns

Optimize Test Performance

  1. Read references/common/performance-optimization.md - Worker config, caching, CI optimization
  2. Read references/common/detect-open-handles.md - Fix open handles preventing clean exit

Debug Open Handles

  • Read references/common/detect-open-handles.md - Detection commands, common handle types, cleanup patterns

Core Principles

0. Context Efficiency (Temp File Output)

ALWAYS redirect unit test output to temp files, NOT console. Test output can be verbose and bloats agent context.

IMPORTANT: Use unique session ID in filenames to prevent conflicts when multiple agents run.

# Initialize session (once at start of testing session)
export UT_SESSION=$(date +%s)-$$

# Standard pattern - redirect output to temp file (NO console output)
npm test > /tmp/ut-${UT_SESSION}-output.log 2>&1

# Read summary only (last 50 lines)
tail -50 /tmp/ut-${UT_SESSION}-output.log

# Get failure details
grep -B 2 -A 15 "FAIL\|✕" /tmp/ut-${UT_SESSION}-output.log

# Cleanup when done
rm -f /tmp/ut-${UT_SESSION}-*.log /tmp/ut-${UT_SESSION}-*.md

Temp Files (with ${UT_SESSION} unique per agent):

  • /tmp/ut-${UT_SESSION}-output.log - Full test output
  • /tmp/ut-${UT_SESSION}-failures.md - Tracking file for one-by-one fixing
  • /tmp/ut-${UT_SESSION}-debug.log - Debug runs
  • /tmp/ut-${UT_SESSION}-verify.log - Verification runs
  • /tmp/ut-${UT_SESSION}-coverage.log - Coverage output

1. AAA Pattern (Mandatory)

ALL unit tests MUST follow Arrange-Act-Assert:

it('should return user when found', async () => {
  // Arrange
  const userId = 'user-123';
  mockRepository.findById.mockResolvedValue({
    id: userId,
    email: 'test@example.com',
    name: 'Test User',
  });

  // Act
  const result = await target.getUser(userId);

  // Assert
  expect(result).toEqual({
    id: userId,
    email: 'test@example.com',
    name: 'Test User',
  });
  expect(mockRepository.findById).toHaveBeenCalledWith(userId);
});

2. Use target for SUT

Always name the system under test as target:

let target: UserService;
let mockRepository: DeepMocked<UserRepository>;

3. DeepMocked Pattern

Use @golevelup/ts-jest for type-safe mocks:

import { createMock, DeepMocked } from '@golevelup/ts-jest';

let mockService: DeepMocked<UserService>;

beforeEach(() => {
  mockService = createMock<UserService>();
});

4. Specific Assertions

Assert exact values, not just existence:

// WRONG
expect(result).toBeDefined();
expect(result.id).toBeDefined();

// CORRECT
expect(result).toEqual({
  id: 'user-123',
  email: 'test@example.com',
  name: 'Test User',
});

5. Mock All Dependencies

Mock external services, never real databases for unit tests:

// Unit Test: Mock repository
{ provide: UserRepository, useValue: mockRepository }

// Repository Test: Use in-memory database
const mongoServer = await createMongoMemoryServer();

Standard Test Template

import { Test, TestingModule } from '@nestjs/testing';
import { createMock, DeepMocked } from '@golevelup/ts-jest';
import { MockLoggerService } from 'src/shared/logger/services/mock-logger.service';

describe('UserService', () => {
  let target: UserService;
  let mockRepository: DeepMocked<UserRepository>;

  beforeEach(async () => {
    // Arrange: Create mocks
    mockRepository = createMock<UserRepository>();

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        { provide: UserRepository, useValue: mockRepository },
      ],
    })
      .setLogger(new MockLoggerService())
      .compile();

    target = module.get<UserService>(UserService);
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  describe('getUser', () => {
    it('should return user when found', async () => {
      // Arrange
      mockRepository.findById.mockResolvedValue({
        id: 'user-123',
        email: 'test@example.com',
      });

      // Act
      const result = await target.getUser('user-123');

      // Assert
      expect(result).toEqual({ id: 'user-123', email: 'test@example.com' });
    });

    it('should throw NotFoundException when user not found', async () => {
      // Arrange
      mockRepository.findById.mockResolvedValue(null);

      // Act & Assert
      await expect(target.getUser('invalid')).rejects.toThrow(NotFoundException);
    });
  });
});

Test Coverage Requirements

CategoryPriorityDescription
Happy pathMANDATORYValid inputs producing expected outputs
Edge casesMANDATORYEmpty arrays, null values, boundaries
Error casesMANDATORYNot found, validation failures
Exception behaviorMANDATORYCorrect type, error code, message
Business rulesMANDATORYDomain logic, calculations
Input validationMANDATORYInvalid inputs, type mismatches

Coverage Target: 80%+ for new code


Failure Resolution Protocol

CRITICAL: Fix ONE test at a time. NEVER run full suite repeatedly while fixing.

When unit tests fail:

  1. Initialize session (once at start): export UT_SESSION=$(date +%s)-$$
  2. Create tracking file: /tmp/ut-${UT_SESSION}-failures.md with all failing tests
  3. Select ONE failing test - work on only this test
  4. Run ONLY that test (never full suite): npm test -- -t "test name" > /tmp/ut-${UT_SESSION}-debug.log 2>&1 tail -50 /tmp/ut-${UT_SESSION}-debug.log
  5. Fix the issue - analyze error, make targeted fix
  6. Verify fix - run same test 3-5 times: for i in {1..5}; do npm test -- -t "test name" > /tmp/ut-${UT_SESSION}-run$i.log 2>&1 && echo "Run $i: PASS" || echo "Run $i: FAIL"; done
  7. Mark as FIXED in tracking file
  8. Move to next failing test - repeat steps 3-7
  9. Run full suite ONLY ONCE after ALL individual tests pass
  10. Cleanup: rm -f /tmp/ut-${UT_SESSION}-*.log /tmp/ut-${UT_SESSION}-*.md

WHY: Running full suite wastes time and context. Each failing test pollutes output, making debugging harder.


Naming Conventions

Test Files

  • Pattern: *.spec.ts
  • Location: Co-located with source file

Test Structure

describe('ClassName', () => {
  describe('methodName', () => {
    it('should [expected behavior] when [condition]', () => {});
  });
});

Variable Names

VariableConvention
SUTtarget
Mocksmock prefix (mockRepository, mockService)
Mock TypeDeepMocked<T>

What NOT to Unit Test

Do NOT create unit tests for:

  • Interfaces - Type definitions only, no runtime behavior
  • Enums - Static value mappings, no logic to test
  • Constants - Static values, no behavior
  • Type aliases - Type definitions only
  • Plain DTOs - Data structures without logic

Only test files containing executable logic (classes with methods, functions with behavior).


Anti-Patterns to Avoid

Don'tWhyDo Instead
Assert only existenceDoesn't catch wrong valuesAssert specific values
Conditional assertionsNon-deterministicSeparate test cases
Test private methodsCouples to implementationTest via public interface
Share state between testsCauses flaky testsFresh setup in beforeEach
Mock repositories in servicesTests implementationMock interfaces
Skip mock verificationDoesn't validate behaviorVerify mock calls
Test interfaces/enums/constantsNo behavior to testSkip these files

Checklist

Setup:

  • Use target for system under test
  • Use mock prefix for all mocks
  • Use DeepMocked<T> type
  • Include .setLogger(new MockLoggerService())
  • Follow AAA pattern with comments
  • Reset mocks in afterEach

Coverage:

  • Happy path tests for all public methods
  • Edge case tests (empty, null, boundaries)
  • Error case tests (not found, validation failures)
  • Exception type and error code verification
  • Mock call verification (parameters + count)

Quality:

  • 80%+ coverage on new code
  • No assertions on log calls
  • No test interdependence
  • Tests fail when any field differs

平台分布

Codex

37.7%
按下载量换算802

Claude

26.8%
按下载量换算570

Cursor

18.51%
按下载量换算394

Gemini CLI

8.29%
按下载量换算176

安全审计

Gen Agent Trust Hub

未通过

Socket

通过

Snyk

通过

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills