testing-unit
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePurpose
用途
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 to replace real implementations.
jest.mock('module') - Stubbing: Define stub responses, like in pytest using to fake object methods.
monkeypatch.setattr() - Isolation: Run tests in isolation, such as using Go's testify to assert without side effects, or JUnit5's for isolated file operations.
@TempDir - Framework-Specific: Support for Jest/Vitest assertions (e.g., ), pytest fixtures for setup/teardown, RSpec's
expect().toBe()for mocks, XCTest'sdoublefor isolation, and JUnit5'ssetUp()annotations.@Mock - Config Formats: Use Jest's with
jest.config.jsfor custom mocks; pytest's{ testEnvironment: 'node', setupFilesAfterEnv: ['<rootDir>/setupTests.js'] }withpytest.inifor verbose output.[pytest] addopts = -v
- Mock功能:为函数或模块创建Mock,例如在Jest中使用替换真实实现。
jest.mock('module') - 桩函数创建:定义桩函数响应,比如在pytest中使用模拟对象方法。
monkeypatch.setattr() - 测试隔离:在隔离环境中运行测试,例如使用Go的testify进行无副作用的断言,或使用JUnit5的实现隔离的文件操作。
@TempDir - 框架专属支持:支持Jest/Vitest断言(如)、pytest的测试夹具(fixtures)用于初始化/清理、RSpec的
expect().toBe()创建Mock、XCTest的double实现隔离,以及JUnit5的setUp()注解。@Mock - 配置格式:使用Jest的配置自定义Mock,示例:
jest.config.js;使用pytest的{ testEnvironment: 'node', setupFilesAfterEnv: ['<rootDir>/setupTests.js'] }配置详细输出,示例: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 blocks; in pytest, use fixtures for shared setup. Always isolate tests by avoiding global state—use in Jest or in pytest.
describe()beforeEach()@pytest.fixture(scope='function')执行单元测试任务可遵循以下步骤:1) 识别需要Mock的依赖项(如HTTP调用)。2) 在测试文件中设置Mock或桩函数。3) 编写断言验证输出。4) 使用合适的参数运行测试。对于TDD,先编写一个失败的测试,再实现对应代码。在Jest中,使用块组织测试;在pytest中,使用测试夹具(fixtures)实现共享初始化。始终通过避免全局状态来隔离测试——在Jest中使用,或在pytest中使用。
describe()beforeEach()@pytest.fixture(scope='function')Common Commands/API
常用命令/API
- Jest/Vitest: Run tests with for interactive mode; mock modules via
npx jest --watchAll. API: Usejest.mock('axios', () => ({ get: jest.fn().mockResolvedValue({ data: {} }) }));for assertions.expect(value).toEqual(expected) - pytest: Execute with for coverage; stub functions with
pytest tests/ -v --cov. API: Leveragedef test_function(monkeypatch): monkeypatch.setattr('module.func', lambda: 'stubbed')for isolation, e.g.,@pytest.fixture.def mock_db(): return {'query': lambda: []} - Go (testify): Build with and use
go test -v ./...from testify; e.g.,mock.Mock.mockCtrl := gomock.NewController(t); mockObj := NewMockInterface(mockCtrl); mockObj.EXPECT().Method().Return(value) - RSpec: Run via ; create doubles with
rspec spec/. API: Usedouble('Object', method: -> 'stubbed').expect { code }.to change { something } - XCTest: Compile and run with ; mock in Swift using
xcodebuild teststubs, e.g.,protocol.class MockService: ServiceProtocol { func fetchData() -> Data { return Data() } } - JUnit5: Execute via ; use Mockito with
./gradlew test. If integrating external services, set env vars like@ExtendWith(MockitoExtension.class) public class TestClass { @Mock private Dependency dep; @InjectMocks private ClassUnderTest cut; }for authentication in tests.$API_KEY
- Jest/Vitest:使用进入交互式模式运行测试;通过
npx jest --watchAllMock模块。API:使用jest.mock('axios', () => ({ get: jest.fn().mockResolvedValue({ data: {} }) }))进行断言。expect(value).toEqual(expected) - pytest:执行查看测试覆盖率;使用如下代码桩化函数:
pytest tests/ -v --cov。API:利用def test_function(monkeypatch): monkeypatch.setattr('module.func', lambda: 'stubbed')实现隔离,示例:@pytest.fixture。def mock_db(): return {'query': lambda: []} - Go (testify):执行构建测试,使用testify的
go test -v ./...;示例:mock.Mock。mockCtrl := gomock.NewController(t); mockObj := NewMockInterface(mockCtrl); mockObj.EXPECT().Method().Return(value) - RSpec:通过运行测试;使用
rspec spec/创建替身对象。API:使用double('Object', method: -> 'stubbed')。expect { code }.to change { something } - XCTest:使用编译并运行测试;在Swift中通过
xcodebuild test创建桩函数,示例:protocol。class MockService: ServiceProtocol { func fetchData() -> Data { return Data() } } - JUnit5:通过执行测试;结合Mockito使用,示例:
./gradlew test。若集成外部服务,可在测试中设置环境变量如@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 . For multi-language projects, use a monorepo setup with tools like Nx for Jest and pytest. Configure environment variables for secrets, e.g., export in your test runner. Link with code coverage tools like Istanbul for Jest or Coverage.py for pytest; ensure mocks respect these by using flags when debugging. For API-dependent tests, inject env vars like into your test command, e.g., .
run: npm test$DATABASE_URL--no-cov$SERVICE_API_KEYpytest --api-key=$SERVICE_API_KEY可将该技能通过在CI/CD流水线中嵌入单元测试来集成,例如在GitHub Actions工作流中添加执行Jest测试。对于多语言项目,可使用Nx等工具构建单体仓库(monorepo)来管理Jest和pytest。配置环境变量存储敏感信息,例如在测试运行器中导出。与代码覆盖率工具集成,如Jest的Istanbul或pytest的Coverage.py;调试时可使用参数确保Mock不会影响覆盖率统计。对于依赖API的测试,可在测试命令中注入环境变量,例如。
run: npm test$DATABASE_URL--no-covpytest --api-key=$SERVICE_API_KEYError Handling
错误处理
Handle common errors prescriptively: For assertion failures in Jest, check stack traces and use to debug mocks; if a mock isn't called, add assertions. In pytest, catch fixture errors by wrapping in try/except, e.g., . For Go, use testify's to fail tests on errors. In RSpec, handle doubles with . For JUnit5, use for expected failures. Always isolate error-prone code with stubs to prevent cascading failures; rerun with verbose flags like or for detailed output.
jest.fn().mockImplementation().toHaveBeenCalled()def test_with_fixture(fix): try: fix.setup() except Exception as e: pytest.fail(str(e))assert.NoError(t, err)allow(double).to receive(:method).and_raise(Error)@Test(expected = Exception.class)jest --debugpytest -s针对常见错误采取预设处理方案:Jest中断言失败时,检查堆栈跟踪并使用调试Mock;若Mock未被调用,添加断言。在pytest中,通过try/except捕获夹具错误,示例:。在Go中,使用testify的在出现错误时终止测试。在RSpec中,使用处理替身对象的错误。在JUnit5中,使用标记预期失败的测试。始终使用桩函数隔离易出错的代码,防止连锁失败;使用详细参数(如或)重新运行测试以获取详细输出。
jest.fn().mockImplementation().toHaveBeenCalled()def test_with_fixture(fix): try: fix.setup() except Exception as e: pytest.fail(str(e))assert.NoError(t, err)allow(double).to receive(:method).and_raise(Error)@Test(expected = Exception.class)jest --debugpytest -sConcrete Usage Examples
实际使用示例
-
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'); }); -
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
-
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'); }); -
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)