Token导航 LogoToken导航

Agent Skill · 开发

javascript-testing(JavaScript 测试)

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

javascript-testing 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为操作浏览器;许可证为 MIT,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 17,066。

总安装 445周安装 18GitHub Stars 2下载 140核验 2026-05-01

安装说明

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

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/shino369/claude-code-personal-workspace --skill javascript-testing

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

全面覆盖 JavaScript 测试策略,包括单元与集成测试。适用于 Jest、Mocha 等主流测试框架支持。使用时应合理划分测试层级,避免过度测试。javascript-testing 属于开发类 Skill,可作为该场景下的辅助能力补充。建议 mock 外部依赖以提高测试速度与稳定性。

安装方式:从个人工作空间获取,可能含私有配置。

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

上手步骤

4 步
  1. 1

    确认自己的宿主工具

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

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/shino369/claude-code-personal-workspace --skil…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

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

  4. 4

    按最小权限试用

    它需要操作浏览器,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

javascript-testing 怎么安装?

在终端执行 npx skills add https://github.com/shino369/claude-code-personal-workspace --skill javascri…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

javascript-testing 支持哪些 AI 工具?

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

javascript-testing 需要什么权限?

权限级别是操作浏览器。该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

javascript-testing 是免费的吗?

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

javascript-testing 用的人多吗?

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

javascript-testing 安全吗?

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

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

值得选的地方

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

先想清楚的地方

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

适不适合你

更适合

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

不太适合

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

开发类 Skill 对比

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

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
javascript-testing

JavaScript 测试 · 本页

4452操作浏览器MIT通过

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

SKILL.md 原文

JavaScript Testing Best Practices

Overview

Comprehensive guidance for writing high-quality JavaScript/Node.js tests using Vitest with 100% code coverage.

Testing Framework: Vitest

Why Vitest:

  • Native ESM support (no experimental flags)
  • Seamless JSDOM integration
  • Faster than Jest
  • Jest-compatible API
  • Built-in coverage with v8

Test structure:

your-script-dir/
├── script.js
└── __tests__/
    └── script.test.js

Vitest Globals

Globals available automatically - no imports needed:

describe('myFunction', () => {
  test('should work', () => {
    expect(true).toBe(true);
  });

  beforeEach(() => {
    /* Setup */
  });
  afterEach(() => {
    /* Cleanup */
  });
});

Available globals: describe, test, it, expect, beforeEach, afterEach, beforeAll, afterAll, vi

Only import vi when mocking:

import { vi } from 'vitest';
vi.mock('module-name');

Coverage Requirements

100% Required For

  • All scripts in .claude/hooks/
  • All scripts in .claude/skills/
  • All utilities in utils/
  • Business logic scripts
  • Data processing scripts
  • API interaction scripts

Check coverage:

pnpm test:coverage
# Must show 100% for: Statements, Branches, Functions, Lines

Tests Optional For

  • One-off automation scripts
  • Shell command wrappers
  • Throwaway/experimental scripts in output/tasks/

Core Principles

1. Rarely Use Coverage Ignore

General Rule: Refactor code to be testable instead of ignoring coverage.

❌ Don't ignore testable business logic:

/* c8 ignore next */
export function calculateTotal(items) {
  // This SHOULD be tested!
  return items.reduce((sum, item) => sum + item.price, 0);
}

✅ Exception - Browser Automation / Integration Code:

Use /* c8 ignore start */ and /* c8 ignore stop */ for code that runs in browser context or requires complex integration setup:

// Browser automation (Playwright, Puppeteer)
/* c8 ignore start -- Browser automation code, tested through integration tests */
export async function fetchContent(url) {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto(url);

  // Browser context code
  const data = await page.evaluate(() => {
    return document.querySelector('h1').innerText;
  });

  await browser.close();
  return data;
}
/* c8 ignore stop */

// CLI entry points
/* c8 ignore start -- CLI entry point, tested through integration tests */
export async function main() {
  // Parse args, handle I/O, etc.
  const args = process.argv.slice(2);
  // ... CLI logic
}
/* c8 ignore stop */

When to use c8 ignore:

  • Browser automation code (Playwright/Puppeteer page interactions)
  • CLI entry points with process.exit() and argument parsing
  • Code that runs in different contexts (browser vs Node.js)
  • Complex integration points that require real dependencies

Requirements when using c8 ignore:

  1. Extract testable logic: Move business logic into separate, testable functions
  2. Create integration tests: Write integration test file (*.integration.test.js) to cover the ignored code
  3. Add comment explaining why: /* c8 ignore start -- Reason why and how it's tested */
  4. Minimize ignored code: Keep ignored blocks as small as possible

✅ Instead - Refactor for testability:

// Extract business logic (testable)
export function processInput(data) {
  return transform(data);
}

// Thin I/O wrapper
function main() {
  const data = readInput();
  const result = processInput(data); // Tested!
  writeOutput(result);
}

2. Separate I/O from Business Logic

❌ Untestable:

function main() {
  process.stdin.on('data', (chunk) => {
    // All logic mixed with I/O
    const data = JSON.parse(chunk);
    const result = complexProcessing(data);
    writeToFile(result);
  });
}

✅ Testable:

export function processHookInput(input) {
  const result = complexProcessing(input);
  return result;
}

function main() {
  process.stdin.on('data', (chunk) => {
    const data = JSON.parse(chunk);
    processHookInput(data); // Tested separately
  });
}

3. Export for Testing

export function main() {
  if (process.argv.length !== 3) {
    console.error('Usage: ...');
    process.exit(1);
  }
  // ... logic
}

runIfMain(import.meta.url, main);

4. Test All Branches

export function processFile(filePath) {
  if (!filePath) throw new Error('Required'); // Branch 1
  if (!fs.existsSync(filePath)) throw new Error('Not found'); // Branch 2
  return fs.readFileSync(filePath); // Branch 3
}

// Test ALL branches
describe('processFile', () => {
  test('missing path', () => expect(() => processFile()).toThrow('Required'));
  test('not found', () => expect(() => processFile('x')).toThrow('Not found'));
  test('exists', () => {
    fs.writeFileSync('t.txt', 'c');
    expect(processFile('t.txt').toString()).toBe('c');
    fs.unlinkSync('t.txt');
  });
});

5. Test Error Paths

Test both success and error paths for every function:

export async function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error('Fetch failed');
    return await response.json();
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

// Test both paths
test('success', async () => {
  global.fetch = vi.fn(() =>
    Promise.resolve({
      ok: true,
      json: () => Promise.resolve({ data: 'test' }),
    })
  );
  expect(await fetchData('url')).toEqual({ data: 'test' });
});

test('failure', async () => {
  global.fetch = vi.fn(() => Promise.resolve({ ok: false }));
  await expect(fetchData('url')).rejects.toThrow('Fetch failed');
});

Test Organization

Arrange-Act-Assert

test('should calculate total', () => {
  const items = [
    { price: 10, qty: 2 },
    { price: 5, qty: 3 },
  ]; // Arrange
  const total = calculateTotal(items); // Act
  expect(total).toBe(35); // Assert
});

Descriptive Names

✅ test('should throw ValidationError when email invalid') ❌ test('works') or test('test1')

One Focus per Test

✅ Separate tests for status code, headers, body ❌ One test checking 10 different things

Test Cleanup

describe('file operations', () => {
  const testDir = 'test_files';

  beforeAll(() => fs.mkdirSync(testDir, { recursive: true }));
  afterAll(() => fs.rmSync(testDir, { recursive: true, force: true }));

  beforeEach(() => fs.writeFileSync(`${testDir}/temp.txt`, 'initial'));
  afterEach(() => {
    if (fs.existsSync(`${testDir}/temp.txt`)) {
      fs.unlinkSync(`${testDir}/temp.txt`);
    }
  });

  test('modifies file', () => {
    modifyFile(`${testDir}/temp.txt`);
    expect(fs.readFileSync(`${testDir}/temp.txt`, 'utf8')).toBe('modified');
  });
});

Running Tests

pnpm test                  # Run all tests
pnpm test:watch            # Watch mode
pnpm test:coverage         # With coverage
pnpm test script.test.js   # Specific file
pnpm test --grep "pattern" # Match pattern

Advanced Topics

See detailed guides:

mocking-guide.md - Mocking patterns:

  • Module/function/fs mocking
  • process.exit(), process.argv, env vars
  • Timers, Date, fetch/HTTP
  • When to mock vs use real dependencies

coverage-strategies.md - 100% coverage:

  • Refactoring I/O-heavy code
  • Testing error paths
  • Testing all branches
  • Handling edge cases

Quick Reference

Common Pitfalls

❌ Don't:

  1. Use coverage ignore comments
  2. Skip error paths
  3. Test implementation details
  4. Over-mock (prefer real integrations)
  5. Forget else branch
  6. Assume code is untestable

✅ Do:

  1. Separate I/O from logic
  2. Test all branches/errors
  3. Use real libs (JSDOM, etc.)
  4. Clean up after tests
  5. Descriptive names
  6. One focus per test

Integration Testing

Prefer real dependencies:

import { JSDOM } from 'jsdom';

test('parses HTML', () => {
  const dom = new JSDOM('<h1>Title</h1>');
  const result = extractContent(dom.window.document);
  expect(result.title).toBe('Title');
});

Mock: External APIs, slow/destructive fs ops, timers, process.exit Use real: Pure JS libs, internal modules, data transforms, algorithms

Optimizing Integration Tests

When testing browser automation (Playwright/Puppeteer) or other slow integration points:

1. Combine related tests:

❌ Slow (9 tests, 17+ seconds):

it('should fetch content', async () => {
  /* ... */
}, 2000);
it('should handle custom selectors', async () => {
  /* ... */
}, 2000);
it('should handle custom timeouts', async () => {
  /* ... */
}, 2000);
// Each launches a new browser

✅ Fast (3 tests, <2 seconds):

it('should fetch content with custom options', async () => {
  // Test multiple features in one browser launch
  const result = await fetchContent(url, {
    selector: 'article',
    timeout: 5000,
  });
  expect(result).toContain('content');
  expect(result).toContain('expected text');
  expect(result).toMatch(/^# /); // markdown format
}, 10000);

2. Make delays configurable:

// Auto-detect shorter delays for test environments
export async function fetchContent(url, options = {}) {
  const { waitDelay = null } = options;

  // file:// URLs need less wait time than remote sites
  const defaultDelay = url.startsWith('file://') ? 500 : 2000;
  const actualDelay = waitDelay !== null ? waitDelay : defaultDelay;

  await page.waitForTimeout(actualDelay);
}

3. Combine error scenarios:

it('should handle various error conditions', async () => {
  await expect(fetchContent('invalid-url')).rejects.toThrow();
  await expect(fetchContent('file:///not/found')).rejects.toThrow();
  await expect(fetchContent(url, { timeout: 1 })).rejects.toThrow();
}, 20000);

4. Use c8 ignore for browser automation:

/* c8 ignore start -- Browser automation, tested in integration tests */
export async function fetchContent(url) {
  const browser = await chromium.launch();
  // ... browser automation
  await browser.close();
}
/* c8 ignore stop */

Result: 8-10x faster test suites while maintaining full coverage and integration confidence.

Best Practices

  1. Use Vitest (not Jest)
  2. Import only vi (globals automatic)
  3. Achieve 100% coverage for production
  4. Refactor for testability; use c8 ignore only for browser automation/CLI code
  5. Separate I/O from business logic
  6. Test all branches and errors
  7. Use real dependencies when possible
  8. Write descriptive test names
  9. Clean up after tests
  10. One assertion focus per test
  11. Optimize integration tests by combining related assertions

平台分布

Claude Code

29.62%
按下载量换算41

Antigravity

20.52%
按下载量换算29

windsurf

15.88%
按下载量换算22

trae

12.6%
按下载量换算18

OpenCode

7.83%
按下载量换算11

Cursor

3.38%
按下载量换算5

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

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

继续浏览同类 Skills