Testing Code
Write automated tests for features, validate functionality against acceptance criteria, and ensure code coverage. Use when writing test code, verifying functionality, or adding test coverage to existing code.
What this skill does
# Testing Code
## Core Workflow
Test writing follows a systematic approach: determine scope, understand patterns, map to requirements, write tests, verify coverage.
### 1. Determine Test Scope
**Read project documentation:**
- `docs/user-stories/US-###-*.md` for acceptance criteria to test
- `docs/feature-spec/F-##-*.md` for technical requirements
- `docs/api-contracts.yaml` for API specifications
- Existing test files to understand patterns
**Choose test types needed:**
- **Unit tests:** Individual functions, pure logic, utilities
- **Integration tests:** Multiple components working together, API endpoints
- **Component tests:** UI components, user interactions
- **E2E tests:** Complete user flows, critical paths
- **Contract tests:** API request/response validation
- **Performance tests:** Load, stress, benchmark testing
### 2. Understand Existing Patterns
**Investigate current test approach:**
- Test framework (Jest, Vitest, Pytest, etc.)
- Mocking patterns and utilities
- Test data fixtures and setup/teardown
- Assertion styles
Use `code-finder` agents if unfamiliar with test structure.
### 3. Map Tests to Requirements
Convert 3-5 acceptance criteria to specific test cases across test types:
**Example mapping:**
```markdown
## User Story: US-101 User Login
### Test Cases
1. **Unit: Authentication service**
- validateCredentials() returns true for valid email/password
- validateCredentials() returns false for invalid password
- checkAccountStatus() detects locked accounts
2. **Integration: Login endpoint**
- POST /api/login with valid creds returns 200 + token
- POST /api/login with invalid creds returns 401 + error
- POST /api/login with locked account returns 403
3. **Component: Login form**
- Submitting form calls login API
- Error message displays on 401 response
- Success redirects to /dashboard
4. **E2E: Complete login flow**
- User enters credentials → submits → sees dashboard
- User enters wrong password → sees error → retries successfully
```
### 4. Write Tests
**Unit Test Structure:**
```javascript
describe('AuthService', () => {
describe('validateCredentials', () => {
it('returns true for valid email and password', async () => {
const result = await authService.validateCredentials(
'[email protected]',
'ValidPass123'
);
expect(result).toBe(true);
});
it('returns false for invalid password', async () => {
const result = await authService.validateCredentials(
'[email protected]',
'WrongPassword'
);
expect(result).toBe(false);
});
});
});
```
**Integration Test Structure:**
```javascript
describe('POST /api/auth/login', () => {
beforeEach(async () => {
await resetTestDatabase();
await createTestUser({
email: '[email protected]',
password: 'Test123!'
});
});
it('returns 200 and token for valid credentials', async () => {
const response = await request(app)
.post('/api/auth/login')
.send({ email: '[email protected]', password: 'Test123!' });
expect(response.status).toBe(200);
expect(response.body).toHaveProperty('token');
expect(response.body.token).toMatch(/^eyJ/); // JWT format
});
it('returns 401 for invalid password', async () => {
const response = await request(app)
.post('/api/auth/login')
.send({ email: '[email protected]', password: 'WrongPassword' });
expect(response.status).toBe(401);
expect(response.body.error).toBe('Invalid credentials');
});
});
```
**Component Test Structure:**
```javascript
describe('LoginForm', () => {
it('submits form with valid data', async () => {
const mockLogin = jest.fn().mockResolvedValue({ success: true });
render(<LoginForm onLogin={mockLogin} />);
await userEvent.type(screen.getByLabelText(/email/i), '[email protected]');
await userEvent.type(screen.getByLabelText(/password/i), 'Password123');
await userEvent.click(screen.getByRole('button', { name: /log in/i }));
expect(mockLogin).toHaveBeenCalledWith({
email: '[email protected]',
password: 'Password123'
});
});
it('displays error message on API failure', async () => {
const mockLogin = jest.fn().mockRejectedValue(new Error('Invalid credentials'));
render(<LoginForm onLogin={mockLogin} />);
await userEvent.type(screen.getByLabelText(/email/i), '[email protected]');
await userEvent.type(screen.getByLabelText(/password/i), 'wrong');
await userEvent.click(screen.getByRole('button', { name: /log in/i }));
expect(await screen.findByText(/invalid credentials/i)).toBeInTheDocument();
});
});
```
**E2E Test Structure:**
```javascript
test('user can log in successfully', async ({ page }) => {
await page.goto('/login');
await page.fill('[name="email"]', '[email protected]');
await page.fill('[name="password"]', 'Test123!');
await page.click('button:has-text("Log In")');
await page.waitForURL('/dashboard');
expect(page.url()).toContain('/dashboard');
});
```
### 5. Edge Cases & Error Scenarios
Include boundary conditions and error paths:
```javascript
describe('Edge cases', () => {
it('handles empty email gracefully', async () => {
await expect(
authService.validateCredentials('', 'password')
).rejects.toThrow('Email is required');
});
it('handles extremely long password', async () => {
const longPassword = 'a'.repeat(10000);
await expect(
authService.validateCredentials('[email protected]', longPassword)
).rejects.toThrow('Password too long');
});
it('handles network timeout', async () => {
jest.spyOn(global, 'fetch').mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 10000))
);
await expect(
authService.login('[email protected]', 'pass')
).rejects.toThrow('Request timeout');
});
});
```
**Edge cases to always include:**
- Empty/null inputs
- Minimum/maximum values
- Invalid formats
- Network failures
- API errors (4xx, 5xx)
- Timeout conditions
- Concurrent operations
### 6. Test Data & Fixtures
Create reusable test fixtures:
```javascript
// tests/fixtures/users.ts
export const validUser = {
email: '[email protected]',
password: 'Test123!',
name: 'Test User'
};
export const invalidUsers = {
noEmail: { password: 'Test123!' },
noPassword: { email: '[email protected]' },
invalidEmail: { email: 'not-an-email', password: 'Test123!' },
weakPassword: { email: '[email protected]', password: '123' }
};
// Use in tests
import { validUser, invalidUsers } from './fixtures/users';
it('validates user data', () => {
expect(validate(validUser)).toBe(true);
expect(validate(invalidUsers.noEmail)).toBe(false);
});
```
### 7. Parallel Test Implementation
When tests are independent (different modules, different test types), spawn parallel agents:
**Pattern 1: Layer-based**
- Agent 1: Unit tests for services/utilities
- Agent 2: Integration tests for API endpoints
- Agent 3: Component tests for UI
- Agent 4: E2E tests for critical flows
**Pattern 2: Feature-based**
- Agent 1: All tests for Feature A
- Agent 2: All tests for Feature B
- Agent 3: All tests for Feature C
**Pattern 3: Type-based**
- Agent 1: All unit tests
- Agent 2: All integration tests
- Agent 3: All E2E tests
### 8. Run & Verify Tests
**Execute test suite:**
```bash
# Unit tests
npm test -- --coverage
# Integration tests
npm run test:integration
# E2E tests
npm run test:e2e
# All tests
npm run test:all
```
**Verify coverage:**
- Aim for >80% code coverage
- 100% coverage of critical paths
- All acceptance criteria have tests
- All error scenarios tested
## Quality Checklist
**Coverage:**
- [ ] All acceptance criteria from user stories tested
- [ ] Happy path covered
- [ ] Edge cases included
- [ ] Error scenarios tested
- [ ] Boundary conditions validated
**Structure:**
- [ ] Tests follow existing patterns
- [ ] Clear test descriptions
- [ ] Proper setup/teardown
- [ ]Related in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.