testing-unit

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Purpose

用途

This skill equips the AI to assist with unit testing using frameworks like Jest/Vitest for JavaScript, pytest for Python, Go's testify, RSpec for Ruby, XCTest for Swift, and JUnit5 for Java. It focuses on mocking dependencies, creating stubs, and ensuring test isolation to verify code behavior in controlled environments.
该技能可让AI协助使用各类单元测试框架开展工作,包括JavaScript的Jest/Vitest、Python的pytest、Go的testify、Ruby的RSpec、Swift的XCTest以及Java的JUnit5。核心聚焦于依赖项Mock、桩函数创建,以及确保测试隔离,从而在受控环境中验证代码行为。

When to Use

适用场景

Use this skill when writing new unit tests, debugging existing ones, or refactoring code that requires isolated testing. Apply it for TDD workflows, mocking external APIs or databases, or ensuring functions work independently. For example, use it when a function depends on a network call—mock it to test locally without real dependencies.
当你需要编写新的单元测试、调试现有测试,或者重构需要隔离测试的代码时,可使用该技能。适用于TDD工作流、Mock外部API或数据库,或者确保函数独立运行的场景。例如,当某个函数依赖网络调用时,可通过Mock该调用在本地进行测试,无需依赖真实服务。

Key Capabilities

核心能力

  • Mocking: Create mocks for functions or modules, e.g., in Jest with
    jest.mock('module')
    to replace real implementations.
  • Stubbing: Define stub responses, like in pytest using
    monkeypatch.setattr()
    to fake object methods.
  • Isolation: Run tests in isolation, such as using Go's testify to assert without side effects, or JUnit5's
    @TempDir
    for isolated file operations.
  • Framework-Specific: Support for Jest/Vitest assertions (e.g.,
    expect().toBe()
    ), pytest fixtures for setup/teardown, RSpec's
    double
    for mocks, XCTest's
    setUp()
    for isolation, and JUnit5's
    @Mock
    annotations.
  • Config Formats: Use Jest's
    jest.config.js
    with
    { testEnvironment: 'node', setupFilesAfterEnv: ['<rootDir>/setupTests.js'] }
    for custom mocks; pytest's
    pytest.ini
    with
    [pytest] addopts = -v
    for verbose output.
  • Mock功能:为函数或模块创建Mock,例如在Jest中使用
    jest.mock('module')
    替换真实实现。
  • 桩函数创建:定义桩函数响应,比如在pytest中使用
    monkeypatch.setattr()
    模拟对象方法。
  • 测试隔离:在隔离环境中运行测试,例如使用Go的testify进行无副作用的断言,或使用JUnit5的
    @TempDir
    实现隔离的文件操作。
  • 框架专属支持:支持Jest/Vitest断言(如
    expect().toBe()
    )、pytest的测试夹具(fixtures)用于初始化/清理、RSpec的
    double
    创建Mock、XCTest的
    setUp()
    实现隔离,以及JUnit5的
    @Mock
    注解。
  • 配置格式:使用Jest的
    jest.config.js
    配置自定义Mock,示例:
    { testEnvironment: 'node', setupFilesAfterEnv: ['<rootDir>/setupTests.js'] }
    ;使用pytest的
    pytest.ini
    配置详细输出,示例:
    [pytest] addopts = -v

Usage Patterns

使用模式

To accomplish unit testing tasks, follow these steps: 1) Identify dependencies to mock (e.g., HTTP calls). 2) Set up mocks or stubs in your test file. 3) Write assertions to verify outputs. 4) Run tests with appropriate flags. For TDD, write a failing test first, then implement code. In Jest, structure tests with
describe()
blocks; in pytest, use fixtures for shared setup. Always isolate tests by avoiding global state—use
beforeEach()
in Jest or
@pytest.fixture(scope='function')
in pytest.
执行单元测试任务可遵循以下步骤:1) 识别需要Mock的依赖项(如HTTP调用)。2) 在测试文件中设置Mock或桩函数。3) 编写断言验证输出。4) 使用合适的参数运行测试。对于TDD,先编写一个失败的测试,再实现对应代码。在Jest中,使用
describe()
块组织测试;在pytest中,使用测试夹具(fixtures)实现共享初始化。始终通过避免全局状态来隔离测试——在Jest中使用
beforeEach()
,或在pytest中使用
@pytest.fixture(scope='function')

Common Commands/API

常用命令/API

  • Jest/Vitest: Run tests with
    npx jest --watchAll
    for interactive mode; mock modules via
    jest.mock('axios', () => ({ get: jest.fn().mockResolvedValue({ data: {} }) }));
    . API: Use
    expect(value).toEqual(expected)
    for assertions.
  • pytest: Execute with
    pytest tests/ -v --cov
    for coverage; stub functions with
    def test_function(monkeypatch): monkeypatch.setattr('module.func', lambda: 'stubbed')
    . API: Leverage
    @pytest.fixture
    for isolation, e.g.,
    def mock_db(): return {'query': lambda: []}
    .
  • Go (testify): Build with
    go test -v ./...
    and use
    mock.Mock
    from testify; e.g.,
    mockCtrl := gomock.NewController(t); mockObj := NewMockInterface(mockCtrl); mockObj.EXPECT().Method().Return(value)
    .
  • RSpec: Run via
    rspec spec/
    ; create doubles with
    double('Object', method: -> 'stubbed')
    . API: Use
    expect { code }.to change { something }
    .
  • XCTest: Compile and run with
    xcodebuild test
    ; mock in Swift using
    protocol
    stubs, e.g.,
    class MockService: ServiceProtocol { func fetchData() -> Data { return Data() } }
    .
  • JUnit5: Execute via
    ./gradlew test
    ; use Mockito with
    @ExtendWith(MockitoExtension.class) public class TestClass { @Mock private Dependency dep; @InjectMocks private ClassUnderTest cut; }
    . If integrating external services, set env vars like
    $API_KEY
    for authentication in tests.
  • Jest/Vitest:使用
    npx jest --watchAll
    进入交互式模式运行测试;通过
    jest.mock('axios', () => ({ get: jest.fn().mockResolvedValue({ data: {} }) }))
    Mock模块。API:使用
    expect(value).toEqual(expected)
    进行断言。
  • pytest:执行
    pytest tests/ -v --cov
    查看测试覆盖率;使用如下代码桩化函数:
    def test_function(monkeypatch): monkeypatch.setattr('module.func', lambda: 'stubbed')
    。API:利用
    @pytest.fixture
    实现隔离,示例:
    def mock_db(): return {'query': lambda: []}
  • Go (testify):执行
    go test -v ./...
    构建测试,使用testify的
    mock.Mock
    ;示例:
    mockCtrl := gomock.NewController(t); mockObj := NewMockInterface(mockCtrl); mockObj.EXPECT().Method().Return(value)
  • RSpec:通过
    rspec spec/
    运行测试;使用
    double('Object', method: -> 'stubbed')
    创建替身对象。API:使用
    expect { code }.to change { something }
  • XCTest:使用
    xcodebuild test
    编译并运行测试;在Swift中通过
    protocol
    创建桩函数,示例:
    class MockService: ServiceProtocol { func fetchData() -> Data { return Data() } }
  • JUnit5:通过
    ./gradlew test
    执行测试;结合Mockito使用,示例:
    @ExtendWith(MockitoExtension.class) public class TestClass { @Mock private Dependency dep; @InjectMocks private ClassUnderTest cut; }
    。若集成外部服务,可在测试中设置环境变量如
    $API_KEY
    用于身份验证。

Integration Notes

集成说明

Integrate this skill by embedding unit tests into CI/CD pipelines, e.g., add Jest to a GitHub Actions workflow with
run: npm test
. For multi-language projects, use a monorepo setup with tools like Nx for Jest and pytest. Configure environment variables for secrets, e.g., export
$DATABASE_URL
in your test runner. Link with code coverage tools like Istanbul for Jest or Coverage.py for pytest; ensure mocks respect these by using
--no-cov
flags when debugging. For API-dependent tests, inject env vars like
$SERVICE_API_KEY
into your test command, e.g.,
pytest --api-key=$SERVICE_API_KEY
.
可将该技能通过在CI/CD流水线中嵌入单元测试来集成,例如在GitHub Actions工作流中添加
run: npm test
执行Jest测试。对于多语言项目,可使用Nx等工具构建单体仓库(monorepo)来管理Jest和pytest。配置环境变量存储敏感信息,例如在测试运行器中导出
$DATABASE_URL
。与代码覆盖率工具集成,如Jest的Istanbul或pytest的Coverage.py;调试时可使用
--no-cov
参数确保Mock不会影响覆盖率统计。对于依赖API的测试,可在测试命令中注入环境变量,例如
pytest --api-key=$SERVICE_API_KEY

Error Handling

错误处理

Handle common errors prescriptively: For assertion failures in Jest, check stack traces and use
jest.fn().mockImplementation()
to debug mocks; if a mock isn't called, add
.toHaveBeenCalled()
assertions. In pytest, catch fixture errors by wrapping in try/except, e.g.,
def test_with_fixture(fix): try: fix.setup() except Exception as e: pytest.fail(str(e))
. For Go, use testify's
assert.NoError(t, err)
to fail tests on errors. In RSpec, handle doubles with
allow(double).to receive(:method).and_raise(Error)
. For JUnit5, use
@Test(expected = Exception.class)
for expected failures. Always isolate error-prone code with stubs to prevent cascading failures; rerun with verbose flags like
jest --debug
or
pytest -s
for detailed output.
针对常见错误采取预设处理方案:Jest中断言失败时,检查堆栈跟踪并使用
jest.fn().mockImplementation()
调试Mock;若Mock未被调用,添加
.toHaveBeenCalled()
断言。在pytest中,通过try/except捕获夹具错误,示例:
def test_with_fixture(fix): try: fix.setup() except Exception as e: pytest.fail(str(e))
。在Go中,使用testify的
assert.NoError(t, err)
在出现错误时终止测试。在RSpec中,使用
allow(double).to receive(:method).and_raise(Error)
处理替身对象的错误。在JUnit5中,使用
@Test(expected = Exception.class)
标记预期失败的测试。始终使用桩函数隔离易出错的代码,防止连锁失败;使用详细参数(如
jest --debug
pytest -s
)重新运行测试以获取详细输出。

Concrete Usage Examples

实际使用示例

  1. Jest Mock Example: To test a function that fetches data, mock the fetch API:
    jest.mock('node-fetch'); const fetch = require('node-fetch'); fetch.mockResolvedValue({ json: () => Promise.resolve({ data: 'mocked' }) }); test('fetches data', async () => { expect(await fetchData()).toEqual('mocked'); });
  2. pytest Fixture Example: To isolate a database-dependent test, use a fixture:
    import pytest @pytest.fixture def mock_db(): return {'query': lambda: [{'id': 1}]} def test_query(mock_db): assert mock_db['query']()[0]['id'] == 1
  1. Jest Mock示例:测试一个获取数据的函数时,Mock fetch API:
    jest.mock('node-fetch'); const fetch = require('node-fetch'); fetch.mockResolvedValue({ json: () => Promise.resolve({ data: 'mocked' }) }); test('fetches data', async () => { expect(await fetchData()).toEqual('mocked'); });
  2. pytest夹具示例:隔离依赖数据库的测试,使用夹具:
    import pytest @pytest.fixture def mock_db(): return {'query': lambda: [{'id': 1}]} def test_query(mock_db): assert mock_db['query']()[0]['id'] == 1

Graph Relationships

关联关系

  • Related to: testing-integration (for broader testing workflows), code-debugging (for fixing test failures)
  • Clusters with: testing (as part of the testing cluster), code-execution (for running tests in isolated environments)
  • Depends on: environment-setup (for managing test dependencies like mocks)
  • 相关技能:testing-integration(用于更广泛的测试工作流)、code-debugging(用于修复测试失败问题)
  • 所属集群:testing(测试集群的一部分)、code-execution(用于在隔离环境中运行测试)
  • 依赖技能:environment-setup(用于管理测试依赖如Mock)