Token导航 LogoToken导航

Agent Skill · 前端设计

javascript-unit-testing(JavaScript unit 测试)

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

javascript-unit-testing 是前端设计类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为可写文件;许可证为 MIT,第三方扫描已通过,按安装量在前端设计类的 10,216 个 Skill 里排第 5,630。

总安装 635周安装 27GitHub Stars 8下载 222核验 2026-05-01

安装说明

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

安装方式

通过对话安装

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

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

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/el-feo/ai-context --skill javascript-unit-testing

这个 Skill 是做什么的

前端设计类 Skill 关注页面结构、视觉规范和组件写法,输出通常是可运行的界面代码。

专注 JavaScript 单元测试编写与 Mock 策略指导。适用于函数级逻辑验证与依赖隔离。javascript-unit-testing 属于前端设计类 Skill,可作为该场景下的辅助能力补充。使用时应优先测试公共接口而非内部实现。建议结合覆盖率报告持续优化测试集。

安装方式:从 AI 上下文库获取,支持多种测试框架适配。

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

上手步骤

4 步
  1. 1

    确认自己的宿主工具

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

  2. 2

    拿到安装命令

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

  3. 3

    安装后重启宿主

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

  4. 4

    按最小权限试用

    它需要可写文件,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

javascript-unit-testing 怎么安装?

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

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

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

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

权限级别是可写文件。该 Skill 可能写入或修改本地文件,使用前需要确认目标目录和修改范围。

javascript-unit-testing 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

javascript-unit-testing 用的人多吗?

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

javascript-unit-testing 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

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

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理前端设计类任务、又不想每次都手写提示词的人。
  • 需要许可证清楚、并且有第三方扫描结果的团队项目。

不太适合

  • 需要厂商级技术支持和 SLA 的生产系统。

前端设计类 Skill 对比

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

前端设计 · Codex、Claude

8,823,360126,072只读MIT通过
vercel-composition-patterns

Vercel 组合模式 · Codex、Claude

3,858,81625,893需要联网MIT通过
vercel-react-native-skills

Vercel React native skills 前端 · Codex、Claude

2,468,66425,878只读MIT通过
adapt

adapt 搜索 · Codex、Claude

2,027,04023,125操作浏览器未明确通过
bolder

bolder 分析 · Codex、Claude

2,004,28823,130只读未明确通过
javascript-unit-testing

JavaScript unit 测试 · 本页

6358可写文件MIT通过

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

SKILL.md 原文

JavaScript Unit Testing

Expert guidance for writing maintainable, trustworthy unit tests in JavaScript and TypeScript using Jest. Based on "The Art of Unit Testing, Third Edition" by Roy Osherove with Vladimir Khorikov (Manning, 2024).

Instructions

When helping users with unit testing:

  1. Understand the context: Identify if they're writing new tests, fixing existing ones, or learning concepts
  2. Apply core principles: Focus on readability, maintainability, and trust in tests
  3. Use appropriate patterns: Select the right testing pattern based on exit point type (return value, state change, or third-party call)
  4. Provide examples: Show concrete code examples following best practices
  5. Reference supporting documentation: Point to references/REFERENCE.md for detailed concepts and references/EXAMPLES.md for more code samples

Core Concepts

Unit of Work

A unit of work is all actions between an entry point (function/method we trigger) and one or more exit points (observable results).

Three types of exit points:

  1. Return value - Function returns a useful value
  2. State change - Observable change in system state
  3. Third-party call - Calling external dependency (logger, database, API)

Good Unit Test Properties

Must have:

  • Fast execution (milliseconds)
  • Fully isolated from other tests
  • Consistent results (no flakiness)
  • Runs in memory (no filesystem, network, database)
  • Clear intent and easy to read

Avoid:

  • Logic in tests (if/else, loops, try/catch)
  • Multiple concerns per test
  • Shared state between tests
  • Testing implementation details vs behavior

Quick Start: Writing Your First Test

Basic Test Structure (AAA Pattern)

test('sum with two numbers returns their sum', () => {
  // Arrange - set up test data
  const input = '1,2';

  // Act - call the unit of work
  const result = sum(input);

  // Assert - verify the outcome
  expect(result).toBe(3);
});

Test Naming (USE Pattern)

Format: [U]nit, [S]cenario, [E]xpectation

// Good examples
test('sum, with two valid numbers, returns their sum', () => { ... });
test('verify, with no uppercase letter, returns false', () => { ... });
test('save, during maintenance window, throws exception', () => { ... });

Organizing Tests

describe('Password Verifier', () => {
  describe('one uppercase rule', () => {
    test('given no uppercase, returns false', () => {
      const verifier = makeVerifier([oneUpperCaseRule]);
      expect(verifier.verify('abc')).toBe(false);
    });

    test('given one uppercase, returns true', () => {
      const verifier = makeVerifier([oneUpperCaseRule]);
      expect(verifier.verify('Abc')).toBe(true);
    });
  });
});

Use factory methods instead of beforeEach() to avoid scroll fatigue and keep tests self-contained.

Testing Different Exit Points

Return Value Testing (Easiest)

test('processes input and returns result', () => {
  const result = calculateTotal([10, 20, 30]);
  expect(result).toBe(60);
});

State-Based Testing

test('adds item to cart and updates count', () => {
  const cart = new ShoppingCart();

  cart.addItem('apple');

  expect(cart.itemCount()).toBe(1);
  expect(cart.contains('apple')).toBe(true);
});

Interaction Testing (Use Sparingly)

Only for testing third-party calls (exit points):

test('save calls logger with correct message', () => {
  const mockLogger = { info: jest.fn() };
  const repository = new Repository(mockLogger);

  repository.save({ id: 1, name: 'test' });

  expect(mockLogger.info).toHaveBeenCalledWith('Saved item 1');
});

Important: Use mocks only for exit points. Have one mock per test maximum. Most tests (95%+) should be return-value or state-based.

Breaking Dependencies

When to Break Dependencies

Break dependencies when code relies on:

  • Time (Date.now(), moment())
  • Random values (Math.random())
  • Network calls (fetch, axios)
  • Filesystem (fs.readFile)
  • Databases
  • External services

Dependency Injection Patterns

1. Parameter Injection (Simplest)

// Before - time dependency baked in
const verify = (input) => {
  const day = moment().day(); // Hard to test!
  if (day === 0 || day === 6) throw Error("Weekend!");
};

// After - time injected
const verify = (input, currentDay) => {
  if (currentDay === 0 || currentDay === 6) throw Error("Weekend!");
};

// Test with full control
test('on weekends, throws exception', () => {
  expect(() => verify('input', 0)).toThrow("Weekend!");
});

2. Functional Injection

const verify = (logger) => (input) => {
  logger.info('Verifying');
  return input.length > 5;
};

// Test
test('verify logs attempt', () => {
  const stubLogger = { info: jest.fn() };
  const verifyFn = verify(stubLogger);
  verifyFn('password');
});

3. Constructor Injection (OOP)

class Verifier {
  constructor(private logger: ILogger) {}

  verify(input: string): boolean {
    this.logger.info('Verifying');
    return true;
  }
}

// Test
test('verify calls logger', () => {
  const mockLogger = { info: jest.fn() };
  const verifier = new Verifier(mockLogger);
  verifier.verify('input');
  expect(mockLogger.info).toHaveBeenCalled();
});

Stubs vs Mocks

Stubs (incoming dependencies):

  • Provide fake data/behavior INTO the unit
  • Do NOT assert against them
  • Can have many per test

Mocks (outgoing dependencies):

  • Represent exit points
  • DO assert they were called correctly
  • Should have ONE per test
// Stub - provides data IN
const stubDatabase = {
  getUser: () => ({ id: 1, name: 'John' })
};

// Mock - verifies calls OUT
const mockLogger = {
  info: jest.fn()
};

test('getUserName retrieves name from database and logs', () => {
  const service = new UserService(stubDatabase, mockLogger);

  const name = service.getUserName(1);

  expect(name).toBe('John'); // Return value assertion
  expect(mockLogger.info).toHaveBeenCalledWith('Retrieved user 1'); // Mock assertion
});

Testing Asynchronous Code

Extract Entry Point Pattern

Extract pure logic from async operations:

// Before - everything mixed
const isWebsiteAlive = async () => {
  const resp = await fetch('http://example.com');
  if (!resp.ok) throw resp.statusText;
  const text = await resp.text();
  return text.includes('illustrative')
    ? { success: true }
    : { success: false, status: 'missing text' };
};

// After - extract testable logic
const processFetchContent = (text) => {
  return text.includes('illustrative')
    ? { success: true }
    : { success: false, status: 'missing text' };
};

// Fast, synchronous unit test
test('with good content, returns success', () => {
  const result = processFetchContent('illustrative');
  expect(result.success).toBe(true);
});

Extract Adapter Pattern

Wrap async dependencies behind testable interfaces:

// network-adapter.js - wrapper for fetch
const fetchUrlText = async (url) => {
  const resp = await fetch(url);
  return resp.ok
    ? { ok: true, text: await resp.text() }
    : { ok: false, text: resp.statusText };
};

// website-verifier.js - inject adapter
const isWebsiteAlive = async (network) => {
  const result = await network.fetchUrlText('http://example.com');
  if (!result.ok) throw result.text;
  return result.text.includes('illustrative');
};

// Test with fake adapter (synchronous!)
test('with good content, returns true', async () => {
  const fakeNetwork = {
    fetchUrlText: () => ({ ok: true, text: 'illustrative' })
  };
  const result = await isWebsiteAlive(fakeNetwork);
  expect(result).toBe(true);
});

Testing Timers

test('calls callback after delay', () => {
  jest.useFakeTimers();
  const callback = jest.fn();

  delayedGreeting(callback);

  expect(callback).not.toHaveBeenCalled();
  jest.advanceTimersByTime(1000);
  expect(callback).toHaveBeenCalledWith('hello');

  jest.useRealTimers();
});

Common Antipatterns to Avoid

  1. Logic in tests - No if/else, loops, or try/catch
  2. Multiple mocks per test - One exit point per test
  3. Asserting against stubs - Only assert against mocks
  4. beforeEach() overuse - Use factory methods instead
  5. Testing private methods - Test through public API
  6. Overspecification - Don't test implementation details
  7. Flaky tests - Inject all dependencies for consistency
  8. Shared state - Keep tests fully isolated
  9. Integration tests as unit tests - Use real dependencies sparingly
  10. No test naming convention - Follow USE pattern

Test Quality Checklist

Can you answer YES to all these?

  • ✓ Tests run in under a few minutes (ideally seconds)?
  • ✓ Any team member can run tests on any machine?
  • ✓ Tests give same results every time (no flakiness)?
  • ✓ Tests work without network, database, or filesystem?
  • ✓ One test failure doesn't affect other tests?
  • ✓ Test names clearly explain what they verify?
  • ✓ Tests are easy to read and understand?
  • ✓ When tests fail, you know exactly what broke?

If NO to any → Review the corresponding section in references/REFERENCE.md

Examples

For comprehensive code examples covering all patterns and scenarios, see references/EXAMPLES.md.

Resources

平台分布

Claude Code

26.06%
按下载量换算58

Gemini CLI

23.4%
按下载量换算52

Antigravity

18.75%
按下载量换算42

windsurf

12.93%
按下载量换算29

github-copilot

7.42%
按下载量换算16

Codex

3.67%
按下载量换算8

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

可写文件

该 Skill 可能写入或修改本地文件,使用前需要确认目标目录和修改范围。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

继续浏览同类 Skills