Test Writer
Overview
The Test Writer skill produces comprehensive, maintainable tests following established practices: the test pyramid (unit → integration → e2e), the AAA (Arrange-Act-Assert) pattern, meaningful naming conventions, and effective mocking strategies. It helps determine what to test, how to structure test files, what to mock vs. not mock, and how to set coverage targets. Good tests serve as executable documentation that catches regressions before they reach production.
When to Use
- Writing tests for a new function, class, or module
- Adding tests to untested legacy code before refactoring
- Following Test-Driven Development (TDD) — writing tests before implementation
- Evaluating test coverage and identifying what's missing
- Writing integration tests for API endpoints or database interactions
When NOT to Use
- Setting up CI/CD pipelines or test runners (infrastructure concern)
- Load testing or performance benchmarking (different tooling)
- Writing end-to-end browser automation scripts (use a Playwright/Cypress skill)
- Debugging a failing test (use the debugger skill to find the root cause)
Quick Reference
| Level |
Scope |
Speed |
Mock? |
Target % |
| Unit |
Single function/class |
Fast (<1ms) |
Dependencies |
70–80% of tests |
| Integration |
Multiple modules + real DB/API |
Medium (10–100ms) |
External services only |
15–25% of tests |
| E2E |
Full user journey through UI |
Slow (1–30s) |
Nothing |
5–10% of tests |
| Concept |
Description |
| AAA |
Arrange (set up) → Act (call) → Assert (verify) |
| Naming |
describe('unit') / it('should behavior when condition') |
| Mocking |
Replace dependencies with controlled test doubles |
| Coverage target |
80% line coverage; 100% on critical paths |
| TDD cycle |
Red → Green → Refactor |
Instructions
Identify the unit under test
- Pick a single function, method, or class as the subject.
- List all inputs, outputs, side effects, and error conditions.
- Identify dependencies that need to be mocked (databases, HTTP clients, file system, clocks).
Choose the right test level
- Unit test: test a function in isolation with all dependencies mocked.
- Integration test: test multiple real components together (e.g., service + real DB).
- E2E test: test a full user-facing workflow through the actual UI or API.
Identify test cases
- Happy path: the function works correctly with valid input.
- Edge cases: empty string, empty array, zero, null, very large numbers, boundary values.
- Error cases: invalid input, dependency throws, timeout.
- State variations: first-time user vs. returning user; empty list vs. full list.
Apply the AAA pattern to each test
// Arrange — set up test data and mocks
// Act — call the function under test
// Assert — verify the output or side effects
Apply naming conventions
- Describe block: name of the unit under test —
describe('calculateDiscount')
- It block: "should [expected behavior] when [condition]" —
it('should return 0 when cart is empty')
- Test file: co-locate with source or mirror directory structure:
utils.test.ts, utils.spec.py
Mock strategically
- Mock I/O boundaries: databases, HTTP calls, file system, time, random.
- Do NOT mock the thing you're testing.
- Do NOT mock value objects or pure functions — use real instances.
- Prefer dependency injection over module-level patching for testability.
Assert precisely
- Assert on the exact expected value, not just that "something was called."
- Verify side effects: was the correct database method called with the correct args?
- For error cases: assert the exact error type and message.
- Avoid asserting on internal implementation details that could change without breaking behavior.
Check coverage
- Run coverage report; target 80%+ line coverage on business logic.
- 100% coverage on security-critical paths (auth, payment, data validation).
- Untested branches show up as risk — prioritize covering error paths.
Examples
Example 1: Write unit tests for a utility function (JavaScript/Jest)
Input: A calculateDiscount function to test:
// discount.js
export function calculateDiscount(price, userTier) {
if (price <= 0) throw new Error('Price must be positive');
const rates = { silver: 0.05, gold: 0.10, platinum: 0.20 };
const rate = rates[userTier] ?? 0;
return Math.round(price * rate * 100) / 100;
}
Output:
// discount.test.js
import { calculateDiscount } from './discount';
describe('calculateDiscount', () => {
describe('happy path', () => {
it('should apply 5% discount for silver tier', () => {
// Arrange
const price = 100;
const tier = 'silver';
// Act
const result = calculateDiscount(price, tier);
// Assert
expect(result).toBe(5.00);
});
it('should apply 10% discount for gold tier', () => {
expect(calculateDiscount(100, 'gold')).toBe(10.00);
});
it('should apply 20% discount for platinum tier', () => {
expect(calculateDiscount(100, 'platinum')).toBe(20.00);
});
it('should return 0 discount for unknown tier', () => {
expect(calculateDiscount(100, 'bronze')).toBe(0);
});
it('should return 0 discount when tier is undefined', () => {
expect(calculateDiscount(100, undefined)).toBe(0);
});
it('should round to 2 decimal places', () => {
// $99.99 * 5% = 4.9995 → rounds to 5.00
expect(calculateDiscount(99.99, 'silver')).toBe(5.00);
});
});
describe('error cases', () => {
it('should throw when price is zero', () => {
expect(() => calculateDiscount(0, 'gold')).toThrow('Price must be positive');
});
it('should throw when price is negative', () => {
expect(() => calculateDiscount(-50, 'gold')).toThrow('Price must be positive');
});
});
describe('edge cases', () => {
it('should handle very small positive price', () => {
expect(calculateDiscount(0.01, 'platinum')).toBe(0.00);
});
it('should handle very large price', () => {
expect(calculateDiscount(1_000_000, 'platinum')).toBe(200_000);
});
});
});
Example 2: Write an integration test for an API endpoint (Node.js/Jest + Supertest)
Input: An Express endpoint to test:
// routes/users.js
router.post('/users', async (req, res) => {
const { email, name } = req.body;
if (!email) return res.status(422).json({ error: 'email is required' });
const existing = await db.users.findByEmail(email);
if (existing) return res.status(409).json({ error: 'email already in use' });
const user = await db.users.create({ email, name });
return res.status(201).json(user);
});
Output:
// routes/users.integration.test.js
import request from 'supertest';
import { app } from '../app';
import { db } from '../db';
// Use a real test database — no mocking of db layer
beforeAll(async () => { await db.migrate.latest(); });
afterAll(async () => { await db.destroy(); });
afterEach(async () => { await db.raw('DELETE FROM users'); }); // clean state
describe('POST /users', () => {
describe('successful creation', () => {
it('should create a user and return 201 with user data', async () => {
// Arrange
const payload = { email: 'alice@example.com', name: 'Alice' };
// Act
const res = await request(app).post('/users').send(payload);
// Assert
expect(res.status).toBe(201);
expect(res.body).toMatchObject({
id: expect.any(String),
email: 'alice@example.com',
name: 'Alice',
createdAt: expect.any(String),
});
// Verify persisted to DB
const saved = await db.users.findByEmail('alice@example.com');
expect(saved).not.toBeNull();
});
});
describe('validation errors', () => {
it('should return 422 when email is missing', async () => {
const res = await request(app).post('/users').send({ name: 'Bob' });
expect(res.status).toBe(422);
expect(res.body.error).toBe('email is required');
});
});
describe('conflict errors', () => {
it('should return 409 when email already exists', async () => {
// Arrange — seed an existing user
await db.users.create({ email: 'carol@example.com', name: 'Carol' });
// Act
const res = await request(app)
.post('/users')
.send({ email: 'carol@example.com', name: 'Carol 2' });
// Assert
expect(res.status).toBe(409);
expect(res.body.error).toBe('email already in use');
});
});
});
Best Practices
- Write tests before code (TDD) to drive better API design
- One logical assertion concept per test — multiple
expect() calls are fine if they verify the same behavior
- Tests should be deterministic: no random data, no time-dependent behavior (mock
Date.now())
- Keep tests fast — slow tests don't get run; unit tests should complete in milliseconds
- Use test factories or builders for complex object setup to avoid repetition
- Test the contract (what), not the implementation (how) — brittle tests couple to internals
Common Mistakes
- Testing implementation details (private methods, internal state) instead of observable behavior
- Not testing error paths and edge cases — happy-path-only tests miss most bugs
- Over-mocking: mocking so much that tests pass even when real integrations are broken
- Using production database in tests without cleanup — tests pollute each other
- Testing framework code (e.g., testing that Express routing works) instead of your business logic
- Ignoring flaky tests — a flaky test is worse than no test (false confidence)
Tips & Tricks
- Use
test.each (Jest) or @pytest.mark.parametrize for table-driven tests with multiple input/output pairs
- Snapshot tests for complex output structures, but review snapshots on every change
--coverage --collectCoverageFrom to see which lines are untested
- Use
faker or factory-boy to generate realistic test data instead of hand-crafting fixtures
- Jest's
jest.useFakeTimers() / Python's freezegun to control time-dependent tests
Related Skills
1---2name: test-writer3description: "Use this skill when writing unit tests, integration tests, or end-to-end tests for existing or new code. Trigger phrases: 'write tests for', 'add test coverage', 'how do I test this', 'TDD this feature'. Not for running or debugging test infrastructure or CI pipelines."4version: 1.0.05author: community6tags: [coding, testing, unit-tests, tdd, jest]7license: MIT8metadata:9 source: https://skillmd.com/skills/xcrrr/test-writer10---1112# Test Writer1314## Overview15The Test Writer skill produces comprehensive, maintainable tests following established practices: the test pyramid (unit → integration → e2e), the AAA (Arrange-Act-Assert) pattern, meaningful naming conventions, and effective mocking strategies. It helps determine what to test, how to structure test files, what to mock vs. not mock, and how to set coverage targets. Good tests serve as executable documentation that catches regressions before they reach production.1617## When to Use18- Writing tests for a new function, class, or module19- Adding tests to untested legacy code before refactoring20- Following Test-Driven Development (TDD) — writing tests before implementation21- Evaluating test coverage and identifying what's missing22- Writing integration tests for API endpoints or database interactions2324## When NOT to Use25- Setting up CI/CD pipelines or test runners (infrastructure concern)26- Load testing or performance benchmarking (different tooling)27- Writing end-to-end browser automation scripts (use a Playwright/Cypress skill)28- Debugging a failing test (use the debugger skill to find the root cause)2930## Quick Reference31| Level | Scope | Speed | Mock? | Target % |32|-------|-------|-------|-------|----------|33| Unit | Single function/class | Fast (<1ms) | Dependencies | 70–80% of tests |34| Integration | Multiple modules + real DB/API | Medium (10–100ms) | External services only | 15–25% of tests |35| E2E | Full user journey through UI | Slow (1–30s) | Nothing | 5–10% of tests |3637| Concept | Description |38|---------|-------------|39| AAA | Arrange (set up) → Act (call) → Assert (verify) |40| Naming | `describe('unit') / it('should behavior when condition')` |41| Mocking | Replace dependencies with controlled test doubles |42| Coverage target | 80% line coverage; 100% on critical paths |43| TDD cycle | Red → Green → Refactor |4445## Instructions46471. **Identify the unit under test**48 - Pick a single function, method, or class as the subject.49 - List all inputs, outputs, side effects, and error conditions.50 - Identify dependencies that need to be mocked (databases, HTTP clients, file system, clocks).51522. **Choose the right test level**53 - **Unit test**: test a function in isolation with all dependencies mocked.54 - **Integration test**: test multiple real components together (e.g., service + real DB).55 - **E2E test**: test a full user-facing workflow through the actual UI or API.56573. **Identify test cases**58 - Happy path: the function works correctly with valid input.59 - Edge cases: empty string, empty array, zero, null, very large numbers, boundary values.60 - Error cases: invalid input, dependency throws, timeout.61 - State variations: first-time user vs. returning user; empty list vs. full list.62634. **Apply the AAA pattern to each test**64 ```65 // Arrange — set up test data and mocks66 // Act — call the function under test67 // Assert — verify the output or side effects68 ```69705. **Apply naming conventions**71 - Describe block: name of the unit under test — `describe('calculateDiscount')`72 - It block: "should [expected behavior] when [condition]" — `it('should return 0 when cart is empty')`73 - Test file: co-locate with source or mirror directory structure: `utils.test.ts`, `utils.spec.py`74756. **Mock strategically**76 - Mock I/O boundaries: databases, HTTP calls, file system, time, random.77 - Do NOT mock the thing you're testing.78 - Do NOT mock value objects or pure functions — use real instances.79 - Prefer dependency injection over module-level patching for testability.80817. **Assert precisely**82 - Assert on the exact expected value, not just that "something was called."83 - Verify side effects: was the correct database method called with the correct args?84 - For error cases: assert the exact error type and message.85 - Avoid asserting on internal implementation details that could change without breaking behavior.86878. **Check coverage**88 - Run coverage report; target 80%+ line coverage on business logic.89 - 100% coverage on security-critical paths (auth, payment, data validation).90 - Untested branches show up as risk — prioritize covering error paths.9192## Examples9394### Example 1: Write unit tests for a utility function (JavaScript/Jest)9596**Input:** A `calculateDiscount` function to test:97```javascript98// discount.js99export function calculateDiscount(price, userTier) {100 if (price <= 0) throw new Error('Price must be positive');101 const rates = { silver: 0.05, gold: 0.10, platinum: 0.20 };102 const rate = rates[userTier] ?? 0;103 return Math.round(price * rate * 100) / 100;104}105```106107**Output:**108```javascript109// discount.test.js110import { calculateDiscount } from './discount';111112describe('calculateDiscount', () => {113 describe('happy path', () => {114 it('should apply 5% discount for silver tier', () => {115 // Arrange116 const price = 100;117 const tier = 'silver';118119 // Act120 const result = calculateDiscount(price, tier);121122 // Assert123 expect(result).toBe(5.00);124 });125126 it('should apply 10% discount for gold tier', () => {127 expect(calculateDiscount(100, 'gold')).toBe(10.00);128 });129130 it('should apply 20% discount for platinum tier', () => {131 expect(calculateDiscount(100, 'platinum')).toBe(20.00);132 });133134 it('should return 0 discount for unknown tier', () => {135 expect(calculateDiscount(100, 'bronze')).toBe(0);136 });137138 it('should return 0 discount when tier is undefined', () => {139 expect(calculateDiscount(100, undefined)).toBe(0);140 });141142 it('should round to 2 decimal places', () => {143 // $99.99 * 5% = 4.9995 → rounds to 5.00144 expect(calculateDiscount(99.99, 'silver')).toBe(5.00);145 });146 });147148 describe('error cases', () => {149 it('should throw when price is zero', () => {150 expect(() => calculateDiscount(0, 'gold')).toThrow('Price must be positive');151 });152153 it('should throw when price is negative', () => {154 expect(() => calculateDiscount(-50, 'gold')).toThrow('Price must be positive');155 });156 });157158 describe('edge cases', () => {159 it('should handle very small positive price', () => {160 expect(calculateDiscount(0.01, 'platinum')).toBe(0.00);161 });162163 it('should handle very large price', () => {164 expect(calculateDiscount(1_000_000, 'platinum')).toBe(200_000);165 });166 });167});168```169170---171172### Example 2: Write an integration test for an API endpoint (Node.js/Jest + Supertest)173174**Input:** An Express endpoint to test:175```javascript176// routes/users.js177router.post('/users', async (req, res) => {178 const { email, name } = req.body;179 if (!email) return res.status(422).json({ error: 'email is required' });180 const existing = await db.users.findByEmail(email);181 if (existing) return res.status(409).json({ error: 'email already in use' });182 const user = await db.users.create({ email, name });183 return res.status(201).json(user);184});185```186187**Output:**188```javascript189// routes/users.integration.test.js190import request from 'supertest';191import { app } from '../app';192import { db } from '../db';193194// Use a real test database — no mocking of db layer195beforeAll(async () => { await db.migrate.latest(); });196afterAll(async () => { await db.destroy(); });197afterEach(async () => { await db.raw('DELETE FROM users'); }); // clean state198199describe('POST /users', () => {200 describe('successful creation', () => {201 it('should create a user and return 201 with user data', async () => {202 // Arrange203 const payload = { email: 'alice@example.com', name: 'Alice' };204205 // Act206 const res = await request(app).post('/users').send(payload);207208 // Assert209 expect(res.status).toBe(201);210 expect(res.body).toMatchObject({211 id: expect.any(String),212 email: 'alice@example.com',213 name: 'Alice',214 createdAt: expect.any(String),215 });216 // Verify persisted to DB217 const saved = await db.users.findByEmail('alice@example.com');218 expect(saved).not.toBeNull();219 });220 });221222 describe('validation errors', () => {223 it('should return 422 when email is missing', async () => {224 const res = await request(app).post('/users').send({ name: 'Bob' });225 expect(res.status).toBe(422);226 expect(res.body.error).toBe('email is required');227 });228 });229230 describe('conflict errors', () => {231 it('should return 409 when email already exists', async () => {232 // Arrange — seed an existing user233 await db.users.create({ email: 'carol@example.com', name: 'Carol' });234235 // Act236 const res = await request(app)237 .post('/users')238 .send({ email: 'carol@example.com', name: 'Carol 2' });239240 // Assert241 expect(res.status).toBe(409);242 expect(res.body.error).toBe('email already in use');243 });244 });245});246```247248## Best Practices249- Write tests before code (TDD) to drive better API design250- One logical assertion concept per test — multiple `expect()` calls are fine if they verify the same behavior251- Tests should be deterministic: no random data, no time-dependent behavior (mock `Date.now()`)252- Keep tests fast — slow tests don't get run; unit tests should complete in milliseconds253- Use test factories or builders for complex object setup to avoid repetition254- Test the contract (what), not the implementation (how) — brittle tests couple to internals255256## Common Mistakes257- Testing implementation details (private methods, internal state) instead of observable behavior258- Not testing error paths and edge cases — happy-path-only tests miss most bugs259- Over-mocking: mocking so much that tests pass even when real integrations are broken260- Using production database in tests without cleanup — tests pollute each other261- Testing framework code (e.g., testing that Express routing works) instead of your business logic262- Ignoring flaky tests — a flaky test is worse than no test (false confidence)263264## Tips & Tricks265- Use `test.each` (Jest) or `@pytest.mark.parametrize` for table-driven tests with multiple input/output pairs266- Snapshot tests for complex output structures, but review snapshots on every change267- `--coverage --collectCoverageFrom` to see which lines are untested268- Use `faker` or `factory-boy` to generate realistic test data instead of hand-crafting fixtures269- Jest's `jest.useFakeTimers()` / Python's `freezegun` to control time-dependent tests270271## Related Skills272- [debugger](../debugger/SKILL.md)273- [code-reviewer](../code-reviewer/SKILL.md)274- [api-designer](../api-designer/SKILL.md)275- [refactorer](../refactorer/SKILL.md)