Token导航 LogoToken导航

Agent Skill · 研究检索

jest-testing-patterns(笑话测试模式)

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

jest-testing-patterns 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证为 MIT,第三方扫描有未通过项,按安装量在研究检索类的 73,675 个 Skill 里排第 41,921。

总安装 1,126周安装 33GitHub Stars 142下载 261核验 2026-05-01

安装说明

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

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/thebushidocollective/han --skill jest-testing-patterns

这个 Skill 是做什么的

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

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

jest-testing-patterns 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

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

上手步骤

4 步
  1. 1

    确认自己的宿主工具

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

  2. 2

    拿到安装命令

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

  3. 3

    安装后重启宿主

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

  4. 4

    按最小权限试用

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

常见问题

6 条

jest-testing-patterns 怎么安装?

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

jest-testing-patterns 支持哪些 AI 工具?

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

jest-testing-patterns 需要什么权限?

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

jest-testing-patterns 是免费的吗?

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

jest-testing-patterns 用的人多吗?

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

jest-testing-patterns 安全吗?

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

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

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。

先想清楚的地方

  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 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调用外部服务未明确有提醒
jest-testing-patterns

笑话测试模式 · 本页

1,126142需要联网MIT未通过

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

SKILL.md 原文

Jest Testing Patterns

Master Jest testing patterns including unit tests, mocks, spies, snapshots, and assertion techniques for comprehensive test coverage. This skill covers the fundamental patterns and practices for writing effective, maintainable tests using Jest.

Basic Test Structure

Test Suite Organization

describe('Calculator', () => {
  describe('add', () => {
    it('should add two positive numbers', () => {
      expect(add(2, 3)).toBe(5);
    });

    it('should add negative numbers', () => {
      expect(add(-2, -3)).toBe(-5);
    });

    it('should handle zero', () => {
      expect(add(0, 5)).toBe(5);
    });
  });

  describe('subtract', () => {
    it('should subtract two numbers', () => {
      expect(subtract(5, 3)).toBe(2);
    });
  });
});

Setup and Teardown

describe('Database operations', () => {
  let db;

  // Runs once before all tests in this describe block
  beforeAll(async () => {
    db = await initializeDatabase();
  });

  // Runs once after all tests in this describe block
  afterAll(async () => {
    await db.close();
  });

  // Runs before each test
  beforeEach(() => {
    db.clear();
  });

  // Runs after each test
  afterEach(() => {
    db.resetMocks();
  });

  it('should insert a record', async () => {
    const result = await db.insert({ name: 'John' });
    expect(result.id).toBeDefined();
  });

  it('should find a record', async () => {
    await db.insert({ id: 1, name: 'John' });
    const result = await db.findById(1);
    expect(result.name).toBe('John');
  });
});

Matchers and Assertions

Common Matchers

describe('Matchers', () => {
  it('should test equality', () => {
    expect(2 + 2).toBe(4); // Strict equality
    expect({ a: 1 }).toEqual({ a: 1 }); // Deep equality
    expect([1, 2, 3]).toStrictEqual([1, 2, 3]); // Strict deep equality
  });

  it('should test truthiness', () => {
    expect(true).toBeTruthy();
    expect(false).toBeFalsy();
    expect(null).toBeNull();
    expect(undefined).toBeUndefined();
    expect('value').toBeDefined();
  });

  it('should test numbers', () => {
    expect(4).toBeGreaterThan(3);
    expect(4).toBeGreaterThanOrEqual(4);
    expect(3).toBeLessThan(4);
    expect(3).toBeLessThanOrEqual(3);
    expect(0.1 + 0.2).toBeCloseTo(0.3, 5);
  });

  it('should test strings', () => {
    expect('team').not.toMatch(/I/);
    expect('Christoph').toMatch(/stop/);
    expect('hello world').toContain('world');
  });

  it('should test arrays and iterables', () => {
    const list = ['apple', 'banana', 'cherry'];
    expect(list).toContain('banana');
    expect(list).toHaveLength(3);
    expect(new Set(list)).toContain('apple');
  });

  it('should test objects', () => {
    expect({ a: 1, b: 2 }).toHaveProperty('a');
    expect({ a: 1, b: 2 }).toHaveProperty('a', 1);
    expect({ a: { b: { c: 1 } } }).toHaveProperty('a.b.c', 1);
  });

  it('should test exceptions', () => {
    expect(() => {
      throw new Error('error');
    }).toThrow();
    expect(() => {
      throw new Error('Invalid input');
    }).toThrow('Invalid input');
    expect(() => {
      throw new Error('Invalid input');
    }).toThrow(/Invalid/);
  });
});

Async Assertions

describe('Async tests', () => {
  // Using async/await
  it('should fetch data', async () => {
    const data = await fetchData();
    expect(data).toBeDefined();
  });

  // Using promises
  it('should fetch data with promise', () => {
    return fetchData().then(data => {
      expect(data).toBeDefined();
    });
  });

  // Testing promise rejection
  it('should handle errors', async () => {
    await expect(fetchInvalidData()).rejects.toThrow('Not found');
  });

  // Using resolves/rejects
  it('should resolve with data', async () => {
    await expect(fetchData()).resolves.toEqual({ id: 1 });
  });

  it('should reject with error', async () => {
    await expect(fetchInvalidData()).rejects.toThrow();
  });
});

Mocking

Function Mocks

describe('Function mocking', () => {
  it('should mock a function', () => {
    const mockFn = jest.fn();
    mockFn('arg1', 'arg2');

    expect(mockFn).toHaveBeenCalled();
    expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2');
    expect(mockFn).toHaveBeenCalledTimes(1);
  });

  it('should mock return values', () => {
    const mockFn = jest.fn()
      .mockReturnValue(42)
      .mockReturnValueOnce(1)
      .mockReturnValueOnce(2);

    expect(mockFn()).toBe(1);
    expect(mockFn()).toBe(2);
    expect(mockFn()).toBe(42);
  });

  it('should mock async functions', async () => {
    const mockFn = jest.fn()
      .mockResolvedValue('success')
      .mockResolvedValueOnce('first call');

    expect(await mockFn()).toBe('first call');
    expect(await mockFn()).toBe('success');
  });

  it('should mock implementations', () => {
    const mockFn = jest.fn((a, b) => a + b);
    expect(mockFn(1, 2)).toBe(3);

    mockFn.mockImplementation((a, b) => a * b);
    expect(mockFn(2, 3)).toBe(6);
  });
});

Module Mocking

// __mocks__/axios.js
export default {
  get: jest.fn(() => Promise.resolve({ data: {} })),
  post: jest.fn(() => Promise.resolve({ data: {} }))
};

// userService.test.js
import axios from 'axios';
import { getUser, createUser } from './userService';

jest.mock('axios');

describe('UserService', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should get user', async () => {
    const mockUser = { id: 1, name: 'John' };
    axios.get.mockResolvedValue({ data: mockUser });

    const user = await getUser(1);

    expect(axios.get).toHaveBeenCalledWith('/users/1');
    expect(user).toEqual(mockUser);
  });

  it('should create user', async () => {
    const newUser = { name: 'Jane' };
    const createdUser = { id: 2, name: 'Jane' };
    axios.post.mockResolvedValue({ data: createdUser });

    const user = await createUser(newUser);

    expect(axios.post).toHaveBeenCalledWith('/users', newUser);
    expect(user).toEqual(createdUser);
  });
});

Partial Mocking

// utils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;

// calculator.test.js
import * as utils from './utils';

jest.mock('./utils', () => ({
  ...jest.requireActual('./utils'),
  multiply: jest.fn()
}));

describe('Calculator', () => {
  it('should use real add function', () => {
    expect(utils.add(2, 3)).toBe(5);
  });

  it('should use mocked multiply function', () => {
    utils.multiply.mockReturnValue(10);
    expect(utils.multiply(2, 3)).toBe(10);
    expect(utils.multiply).toHaveBeenCalledWith(2, 3);
  });
});

Spies

Spying on Methods

describe('Spies', () => {
  it('should spy on object methods', () => {
    const calculator = {
      add: (a, b) => a + b
    };

    const spy = jest.spyOn(calculator, 'add');
    calculator.add(2, 3);

    expect(spy).toHaveBeenCalled();
    expect(spy).toHaveBeenCalledWith(2, 3);
    expect(spy).toHaveReturnedWith(5);

    spy.mockRestore();
  });

  it('should spy and mock implementation', () => {
    const logger = {
      log: (message) => console.log(message)
    };

    const spy = jest.spyOn(logger, 'log').mockImplementation(() => {});
    logger.log('test');

    expect(spy).toHaveBeenCalledWith('test');
    spy.mockRestore();
  });

  it('should spy on getter', () => {
    const obj = {
      get value() {
        return 42;
      }
    };

    const spy = jest.spyOn(obj, 'value', 'get').mockReturnValue(100);
    expect(obj.value).toBe(100);
    spy.mockRestore();
  });
});

Spying on Global Functions

describe('Global spies', () => {
  it('should spy on console.log', () => {
    const spy = jest.spyOn(console, 'log').mockImplementation();
    console.log('test message');

    expect(spy).toHaveBeenCalledWith('test message');
    spy.mockRestore();
  });

  it('should spy on Date', () => {
    const mockDate = new Date('2024-01-01');
    const spy = jest.spyOn(global, 'Date').mockImplementation(() => mockDate);

    expect(new Date()).toBe(mockDate);
    spy.mockRestore();
  });
});

Snapshot Testing

Basic Snapshots

import { render } from '@testing-library/react';
import Button from './Button';

describe('Button component', () => {
  it('should match snapshot', () => {
    const { container } = render(<Button label="Click me" />);
    expect(container.firstChild).toMatchSnapshot();
  });

  it('should match inline snapshot', () => {
    const user = {
      name: 'John Doe',
      age: 30
    };
    expect(user).toMatchInlineSnapshot(`
      {
        "age": 30,
        "name": "John Doe",
      }
    `);
  });
});

Property Matchers

describe('Snapshot with dynamic data', () => {
  it('should match snapshot with property matchers', () => {
    const user = {
      id: generateId(),
      createdAt: new Date(),
      name: 'John Doe'
    };

    expect(user).toMatchSnapshot({
      id: expect.any(String),
      createdAt: expect.any(Date)
    });
  });
});

Custom Serializers

// custom-serializer.js
module.exports = {
  test(val) {
    return val && val.hasOwnProperty('_reactInternalFiber');
  },
  serialize(val, config, indentation, depth, refs, printer) {
    return `<ReactElement ${val.type} />`;
  }
};

// jest.config.js
module.exports = {
  snapshotSerializers: ['./custom-serializer.js']
};

Testing Patterns

Testing React Components

import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Form from './Form';

describe('Form component', () => {
  it('should render form fields', () => {
    render(<Form />);

    expect(screen.getByLabelText('Name')).toBeInTheDocument();
    expect(screen.getByLabelText('Email')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument();
  });

  it('should handle user input', async () => {
    const user = userEvent.setup();
    render(<Form />);

    const nameInput = screen.getByLabelText('Name');
    await user.type(nameInput, 'John Doe');

    expect(nameInput).toHaveValue('John Doe');
  });

  it('should submit form', async () => {
    const onSubmit = jest.fn();
    render(<Form onSubmit={onSubmit} />);

    await userEvent.type(screen.getByLabelText('Name'), 'John Doe');
    await userEvent.type(screen.getByLabelText('Email'), 'john@example.com');
    await userEvent.click(screen.getByRole('button', { name: 'Submit' }));

    await waitFor(() => {
      expect(onSubmit).toHaveBeenCalledWith({
        name: 'John Doe',
        email: 'john@example.com'
      });
    });
  });

  it('should display validation errors', async () => {
    render(<Form />);

    const submitButton = screen.getByRole('button', { name: 'Submit' });
    await userEvent.click(submitButton);

    await waitFor(() => {
      expect(screen.getByText('Name is required')).toBeInTheDocument();
    });
  });
});

Testing Async Operations

describe('Async operations', () => {
  it('should wait for async operation', async () => {
    const promise = fetchData();
    const data = await promise;
    expect(data).toBeDefined();
  });

  it('should use fake timers', () => {
    jest.useFakeTimers();

    const callback = jest.fn();
    setTimeout(callback, 1000);

    expect(callback).not.toHaveBeenCalled();
    jest.advanceTimersByTime(1000);
    expect(callback).toHaveBeenCalled();

    jest.useRealTimers();
  });

  it('should run all timers', () => {
    jest.useFakeTimers();

    const callback1 = jest.fn();
    const callback2 = jest.fn();

    setTimeout(callback1, 1000);
    setTimeout(callback2, 2000);

    jest.runAllTimers();

    expect(callback1).toHaveBeenCalled();
    expect(callback2).toHaveBeenCalled();

    jest.useRealTimers();
  });
});

Testing Error Boundaries

import { render, screen } from '@testing-library/react';
import ErrorBoundary from './ErrorBoundary';

const ThrowError = () => {
  throw new Error('Test error');
};

describe('ErrorBoundary', () => {
  it('should catch errors and display fallback', () => {
    // Suppress console.error for this test
    const spy = jest.spyOn(console, 'error').mockImplementation();

    render(
      <ErrorBoundary>
        <ThrowError />
      </ErrorBoundary>
    );

    expect(screen.getByText('Something went wrong')).toBeInTheDocument();

    spy.mockRestore();
  });

  it('should render children when no error', () => {
    render(
      <ErrorBoundary>
        <div>Content</div>
      </ErrorBoundary>
    );

    expect(screen.getByText('Content')).toBeInTheDocument();
  });
});

Best Practices

  1. Write descriptive test names - Use clear, specific names that explain what the test verifies
  2. Follow AAA pattern - Structure tests with Arrange, Act, Assert sections for clarity
  3. Test behavior, not implementation - Focus on what the code does, not how it does it
  4. Use appropriate matchers - Choose the most specific matcher for better error messages
  5. Mock external dependencies - Isolate unit tests from external services and modules
  6. Clean up after tests - Use afterEach to reset mocks and clean up side effects
  7. Avoid testing private methods - Test public interfaces and trust implementation details
  8. Use setup and teardown hooks effectively - Leverage beforeEach/afterEach for common setup
  9. Test edge cases and error conditions - Don't just test happy paths
  10. Keep tests fast and isolated - Each test should run independently and quickly

Common Pitfalls

  1. Not cleaning up mocks between tests - Leads to test pollution and flaky tests
  2. Testing implementation details - Makes tests brittle and hard to maintain
  3. Overusing snapshots - Snapshots should supplement, not replace, specific assertions
  4. Forgetting to await async operations - Results in false positives and flaky tests
  5. Not using proper matchers - Generic matchers provide poor error messages
  6. Mocking too much - Over-mocking reduces test confidence and value
  7. Writing integration tests as unit tests - Mixing concerns makes tests slow and complex
  8. Not testing error scenarios - Only testing happy paths leaves bugs uncaught
  9. Shared state between tests - Global variables and singletons cause test interdependence
  10. Unclear test names - Vague names make it hard to understand test failures

When to Use This Skill

  • Writing unit tests for functions and classes
  • Testing React components with user interactions
  • Mocking external dependencies and APIs
  • Creating snapshot tests for UI components
  • Testing asynchronous code and promises
  • Implementing spies to verify function calls
  • Testing error handling and edge cases
  • Setting up test fixtures and test data
  • Debugging failing tests and understanding test output
  • Refactoring tests for better maintainability

平台分布

Claude Code

28.46%
按下载量换算74

OpenCode

25.49%
按下载量换算67

Codex

18.74%
按下载量换算49

Antigravity

12.26%
按下载量换算32

windsurf

6.84%
按下载量换算18

Gemini CLI

3.5%
按下载量换算9

安全审计

Gen Agent Trust Hub

未通过

Socket

通过

Snyk

通过

权限和风险

需要联网

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

安装前确认

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

继续浏览同类 Skills