Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问clear审计异常

bun-testBun 测试

Agent Skill

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

总安装

3,058

周安装

130

GitHub Stars

3

下载量

1,071
CodexClaudeCursorGemini CLI

安装说明

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

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/daleseo/bun-skills --skill bun-test

简介

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

  • 适合编写单元测试、端到端测试、测试计划或定位失败日志问题。
  • 基于 Bun 内置测试 runner,兼容 Jest API 且执行速度显著更快。
  • 支持 mocking、spies 和模块模拟等高级测试功能。
  • 使用时需确认项目测试框架、运行命令和夹具数据,避免误改逻辑。

SKILL.md

Bun Test Configuration

Set up Bun's built-in test runner with Jest-compatible APIs and significantly faster execution (3-10x faster than Jest).

Quick Reference

For detailed patterns, see:

  • Jest Migration: jest-migration.md - Complete Jest to Bun migration guide
  • Mocking: mocking.md - Mock functions, spies, module mocking
  • Examples: examples.md - Test patterns for APIs, databases, async code

Core Workflow

1. Check Prerequisites

# Verify Bun installation
bun --version

# Check if project exists
ls -la package.json

2. Determine Testing Needs

Ask the user what type of testing they need:

  • Unit Testing: Test individual functions and modules
  • Integration Testing: Test component interactions
  • API Testing: Test HTTP endpoints
  • Snapshot Testing: Test output consistency

3. Create Test Directory Structure

# Create test directories
mkdir -p tests/{unit,integration,fixtures}

Recommended structure:

project/
├── src/
│   ├── utils.ts
│   └── components/
├── tests/
│   ├── unit/              # Unit tests
│   ├── integration/       # Integration tests
│   ├── fixtures/          # Test data
│   └── setup.ts          # Global setup
├── package.json
└── bunfig.toml           # Test configuration

4. Configure Bun Test

Create bunfig.toml in project root:

[test]
# Preload files before running tests
preload = ["./tests/setup.ts"]

# Code coverage
coverage = true
coverageDir = "coverage"
coverageThreshold = 80

# Timeouts (in milliseconds)
timeout = 5000

# Bail after first failure
bail = false

5. Create Test Setup File

Create tests/setup.ts:

import { beforeAll, afterAll, beforeEach, afterEach } from "bun:test";

// Global test setup
beforeAll(() => {
  console.log("🧪 Starting test suite");
  process.env.NODE_ENV = "test";
});

afterAll(() => {
  console.log("✅ Test suite complete");
});

// Reset mocks before each test
beforeEach(() => {
  // Clear mock state
});

afterEach(() => {
  // Cleanup after each test
});

// Global test utilities
globalThis.testHelpers = {
  wait: (ms: number) => new Promise(resolve => setTimeout(resolve, ms)),
};

6. Write First Test

Create tests/unit/example.test.ts:

import { describe, it, expect, test } from "bun:test";

// Simple test
test("addition works", () => {
  expect(1 + 1).toBe(2);
});

// Describe blocks for organization
describe("Array utilities", () => {
  it("should filter even numbers", () => {
    const numbers = [1, 2, 3, 4, 5, 6];
    const evens = numbers.filter(n => n % 2 === 0);

    expect(evens).toEqual([2, 4, 6]);
    expect(evens).toHaveLength(3);
  });
});

// Async tests
describe("Async operations", () => {
  it("should handle promises", async () => {
    const result = await Promise.resolve(42);
    expect(result).toBe(42);
  });
});

For more test examples (API testing, database testing, etc.), see examples.md.

7. Add Mocking (If Needed)

import { describe, it, expect, mock, spyOn } from "bun:test";

describe("Mock functions", () => {
  it("should create mock functions", () => {
    const mockFn = mock((x: number) => x * 2);

    const result = mockFn(5);

    expect(result).toBe(10);
    expect(mockFn).toHaveBeenCalledTimes(1);
    expect(mockFn).toHaveBeenCalledWith(5);
  });

  it("should spy on methods", () => {
    const obj = {
      method: (x: number) => x * 2,
    };

    const spy = spyOn(obj, "method");

    obj.method(5);

    expect(spy).toHaveBeenCalledWith(5);
    expect(spy).toHaveReturnedWith(10);
  });
});

For advanced mocking patterns, see mocking.md.

8. Update package.json

Add test scripts:

{
  "scripts": {
    "test": "bun test",
    "test:watch": "bun test --watch",
    "test:coverage": "bun test --coverage",
    "test:ui": "bun test --coverage --reporter=html"
  }
}

9. Run Tests

# Run all tests
bun test

# Run specific file
bun test tests/unit/utils.test.ts

# Watch mode
bun test --watch

# With coverage
bun test --coverage

# Filter by name
bun test --test-name-pattern="should handle"

Jest Migration

If migrating from Jest, see jest-migration.md for:

  • Import updates (@jest/globalsbun:test)
  • Mock syntax changes (jest.fn()mock())
  • Configuration migration
  • Compatibility notes

Key changes:

// Before (Jest)
import { describe, it, expect } from '@jest/globals';
const mockFn = jest.fn();

// After (Bun)
import { describe, it, expect, mock } from 'bun:test';
const mockFn = mock();

Common Test Patterns

Testing Functions

import { test, expect } from "bun:test";

function add(a: number, b: number): number {
  return a + b;
}

test("add function", () => {
  expect(add(2, 3)).toBe(5);
  expect(add(-1, 1)).toBe(0);
});

Testing Errors

test("should throw errors", () => {
  const throwError = () => {
    throw new Error("Something went wrong");
  };

  expect(throwError).toThrow("Something went wrong");
  expect(throwError).toThrow(Error);
});

test("should reject promises", async () => {
  const asyncReject = async () => {
    throw new Error("Async error");
  };

  await expect(asyncReject()).rejects.toThrow("Async error");
});

Snapshot Testing

test("should match snapshot", () => {
  const data = {
    id: 1,
    name: "Test User",
    email: "test@example.com",
  };

  expect(data).toMatchSnapshot();
});

test("should match inline snapshot", () => {
  const config = { theme: "dark", language: "en" };

  expect(config).toMatchInlineSnapshot(`
    {
      "theme": "dark",
      "language": "en"
    }
  `);
});

Matchers Reference

Common matchers available:

// Equality
expect(value).toBe(expected);           // ===
expect(value).toEqual(expected);        // Deep equality

// Truthiness
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeDefined();
expect(value).toBeUndefined();

// Numbers
expect(number).toBeGreaterThan(3);
expect(number).toBeLessThan(5);

// Strings
expect(string).toMatch(/pattern/);
expect(string).toContain("substring");

// Arrays
expect(array).toContain(item);
expect(array).toHaveLength(3);

// Objects
expect(object).toHaveProperty("key");
expect(object).toMatchObject({ subset });

// Promises
await expect(promise).resolves.toBe(value);
await expect(promise).rejects.toThrow();

// Mock functions
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledTimes(3);
expect(mockFn).toHaveBeenCalledWith(arg1, arg2);

Test Organization

Setup and Teardown

import { beforeAll, afterAll, beforeEach, afterEach, describe, it } from "bun:test";

describe("User service", () => {
  let db: Database;

  beforeAll(async () => {
    // Setup before all tests
    db = await connectToDatabase();
  });

  afterAll(async () => {
    // Cleanup after all tests
    await db.close();
  });

  beforeEach(async () => {
    // Reset before each test
    await db.clear();
  });

  it("should create user", async () => {
    const user = await db.users.create({ name: "Test" });
    expect(user.id).toBeDefined();
  });
});

Coverage Configuration

View coverage report:

# Generate coverage
bun test --coverage

# View HTML report
bun test --coverage --reporter=html
open coverage/index.html

Set coverage thresholds in bunfig.toml:

[test]
coverage = true
coverageThreshold = 80  # Fail if coverage < 80%

Debugging Tests

# Run with debugger
bun test --inspect

# Verbose output
bun test --verbose

# Show all test results
bun test --reporter=tap

Performance

Bun test is significantly faster than Jest:

  • Jest: ~15 seconds for 100 tests
  • Bun: ~2 seconds for 100 tests

3-10x faster execution!

Completion Checklist

  • ✅ Test directory structure created
  • ✅ bunfig.toml configured
  • ✅ Test setup file created
  • ✅ Example tests written
  • ✅ Package.json scripts updated
  • ✅ Tests run successfully
  • ✅ Coverage configured (if needed)

Next Steps

After basic setup:

  1. Write tests: Add tests for critical business logic
  2. CI/CD: Configure tests to run in your pipeline
  3. Coverage: Set up coverage reporting
  4. Pre-commit: Add pre-commit hooks to run tests
  5. Documentation: Document testing patterns for the team

For detailed implementations, see the reference files linked above.

适合场景

01

用户想查找某类 Agent Skill 时

02

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

03

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

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

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

能力 4

补充不同宿主或平台的使用分布数据

能力 5

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

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

平台分布

Claude Code

26.47%
按下载量换算283

Cursor

23.83%
按下载量换算255

OpenCode

16.81%
按下载量换算180

Codex

12.47%
按下载量换算134

Gemini CLI

7.72%
按下载量换算83

windsurf

3.68%
按下载量换算39

安全审计

Gen Agent Trust Hub

未通过

Socket

通过

Snyk

通过

权限和风险

需要联网

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

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。

来源信息

继续浏览同类 Skills