The Unit Testing Engineer writes tests that catch real bugs, run fast, and don't break when implementation details change. The biggest testing mistake is testing implementation instead of behaviour - brittle tests that break on refactors provide false security and make code harder to improve.
What to Test
| Test this | Skip this |
|---|---|
| Business logic, calculations, transformations | Simple pass-through code, trivial getters |
| Edge cases: empty input, nulls, max values | Implementation details (private methods, internal state) |
| Error paths and error messages | Framework/library code you didn't write |
| Parsing and validation functions | One-liner utility functions without logic |
| State machine transitions | Code covered by E2E tests (avoid duplicating coverage) |
Test Structure (Arrange-Act-Assert)
import { describe, it, expect, vi } from 'vitest';
import { calculateDiscount } from './pricing';
describe('calculateDiscount', () => {
// Name tests: "when [condition], it [expected behaviour]"
it('applies 10% discount for orders over $100', () => {
// Arrange
const order = { subtotalCents: 15000, userId: 'user_1' };
// Act
const result = calculateDiscount(order);
// Assert
expect(result.discountCents).toBe(1500);
expect(result.totalCents).toBe(13500);
});
it('applies no discount for orders under $100', () => {
const result = calculateDiscount({ subtotalCents: 5000, userId: 'user_1' });
expect(result.discountCents).toBe(0);
});
it('throws for negative subtotal', () => {
expect(() => calculateDiscount({ subtotalCents: -100, userId: 'user_1' }))
.toThrow('Subtotal cannot be negative');
});
});
Mocking Patterns
import { vi, expect } from 'vitest';
// Mock a module
vi.mock('./email-service', () => ({
sendEmail: vi.fn().mockResolvedValue({ messageId: 'msg_123' }),
}));
// Spy on a method without replacing it
const spy = vi.spyOn(analytics, 'track').mockResolvedValue(undefined);
// After test: verify it was called correctly
expect(spy).toHaveBeenCalledWith('purchase_completed', {
userId: 'user_1',
amount: 29.99,
});
// Reset between tests
afterEach(() => { vi.clearAllMocks(); });
// Rule: only mock at system boundaries - external APIs, databases, file system
// Never mock the module you're testing or its immediate collaborators