skills/testing/testing-unit/SKILL.md
Unit: Jest/Vitest, pytest, Go test/testify, RSpec, XCTest, JUnit5. Mocking, stubs, isolation
npx skillsauth add alphaonedev/openclaw-graph testing-unitInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
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.
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.
jest.mock('module') to replace real implementations.monkeypatch.setattr() to fake object methods.@TempDir for isolated file operations.expect().toBe()), pytest fixtures for setup/teardown, RSpec's double for mocks, XCTest's setUp() for isolation, and JUnit5's @Mock annotations.jest.config.js with { testEnvironment: 'node', setupFilesAfterEnv: ['<rootDir>/setupTests.js'] } for custom mocks; pytest's pytest.ini with [pytest] addopts = -v for verbose output.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.
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 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 test -v ./... and use mock.Mock from testify; e.g., mockCtrl := gomock.NewController(t); mockObj := NewMockInterface(mockCtrl); mockObj.EXPECT().Method().Return(value).rspec spec/; create doubles with double('Object', method: -> 'stubbed'). API: Use expect { code }.to change { something }.xcodebuild test; mock in Swift using protocol stubs, e.g., class MockService: ServiceProtocol { func fetchData() -> Data { return Data() } }../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.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.
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 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
tools
Root web development: project structure, tooling selection, deployment decisions
development
WebAssembly: Rust/Go/C to WASM, wasm-bindgen, Emscripten, WASM Component Model
development
Vue 3: Composition API script setup, Pinia, Vue Router 4, SFCs, Vite, Nuxt 3
tools
Tailwind CSS 4: utility classes, config, JIT, arbitrary values, darkMode, plugins, shadcn/ui