testing-strategies
Unit, integration, E2E testing and TDD practices
What this skill does
# Testing Strategies
## Overview
Testing pyramid, patterns, and practices for building reliable software.
---
## Testing Pyramid
```
/\
/ \
/ E2E\ Few, slow, expensive
/──────\
/ \
/Integration\ Some, medium speed
/──────────────\
/ \
/ Unit Tests \ Many, fast, cheap
/____________________\
```
| Level | Speed | Scope | Quantity |
|-------|-------|-------|----------|
| Unit | Fast (ms) | Single function/class | Many (70%) |
| Integration | Medium (s) | Multiple components | Some (20%) |
| E2E | Slow (min) | Full system | Few (10%) |
---
## Unit Testing
### Structure: Arrange-Act-Assert
```typescript
describe('calculateDiscount', () => {
it('applies 10% discount for orders over $100', () => {
// Arrange
const order = { items: [{ price: 150 }] };
const discountService = new DiscountService();
// Act
const result = discountService.calculateDiscount(order);
// Assert
expect(result).toBe(15);
});
it('returns 0 for orders under $100', () => {
// Arrange
const order = { items: [{ price: 50 }] };
const discountService = new DiscountService();
// Act
const result = discountService.calculateDiscount(order);
// Assert
expect(result).toBe(0);
});
});
```
### Mocking
```typescript
// Mock dependencies
const mockEmailService = {
send: jest.fn().mockResolvedValue({ success: true })
};
const mockUserRepo = {
findById: jest.fn().mockResolvedValue({ id: '1', email: '[email protected]' })
};
describe('NotificationService', () => {
let service: NotificationService;
beforeEach(() => {
jest.clearAllMocks();
service = new NotificationService(mockEmailService, mockUserRepo);
});
it('sends email to user', async () => {
await service.notifyUser('1', 'Hello!');
expect(mockUserRepo.findById).toHaveBeenCalledWith('1');
expect(mockEmailService.send).toHaveBeenCalledWith(
'[email protected]',
'Hello!'
);
});
it('throws when user not found', async () => {
mockUserRepo.findById.mockResolvedValue(null);
await expect(service.notifyUser('999', 'Hello!'))
.rejects.toThrow('User not found');
});
});
```
### Testing Edge Cases
```typescript
describe('parseAge', () => {
// Happy path
it('parses valid age string', () => {
expect(parseAge('25')).toBe(25);
});
// Edge cases
it('handles zero', () => {
expect(parseAge('0')).toBe(0);
});
it('handles boundary values', () => {
expect(parseAge('1')).toBe(1);
expect(parseAge('150')).toBe(150);
});
// Error cases
it('throws on negative numbers', () => {
expect(() => parseAge('-5')).toThrow('Age cannot be negative');
});
it('throws on non-numeric input', () => {
expect(() => parseAge('abc')).toThrow('Invalid age format');
});
it('throws on empty string', () => {
expect(() => parseAge('')).toThrow('Age is required');
});
// Null/undefined
it('throws on null', () => {
expect(() => parseAge(null as any)).toThrow();
});
});
```
---
## Integration Testing
### API Testing
```typescript
import request from 'supertest';
import { app } from '../app';
import { db } from '../database';
describe('POST /api/users', () => {
beforeEach(async () => {
await db.users.deleteMany({});
});
afterAll(async () => {
await db.disconnect();
});
it('creates a new user', async () => {
const response = await request(app)
.post('/api/users')
.send({
email: '[email protected]',
name: 'Test User'
})
.expect(201);
expect(response.body).toMatchObject({
id: expect.any(String),
email: '[email protected]',
name: 'Test User'
});
// Verify in database
const user = await db.users.findOne({ email: '[email protected]' });
expect(user).not.toBeNull();
});
it('returns 400 for invalid email', async () => {
const response = await request(app)
.post('/api/users')
.send({
email: 'invalid-email',
name: 'Test User'
})
.expect(400);
expect(response.body.error).toBe('Invalid email format');
});
it('returns 409 for duplicate email', async () => {
// Create first user
await request(app)
.post('/api/users')
.send({ email: '[email protected]', name: 'First' });
// Try to create duplicate
const response = await request(app)
.post('/api/users')
.send({ email: '[email protected]', name: 'Second' })
.expect(409);
expect(response.body.error).toBe('Email already exists');
});
});
```
### Database Testing with Testcontainers
```typescript
import { PostgreSqlContainer } from '@testcontainers/postgresql';
import { Pool } from 'pg';
describe('UserRepository', () => {
let container: StartedPostgreSqlContainer;
let pool: Pool;
let repo: UserRepository;
beforeAll(async () => {
container = await new PostgreSqlContainer().start();
pool = new Pool({ connectionString: container.getConnectionUri() });
await runMigrations(pool);
repo = new UserRepository(pool);
}, 60000);
afterAll(async () => {
await pool.end();
await container.stop();
});
beforeEach(async () => {
await pool.query('TRUNCATE users CASCADE');
});
it('creates and retrieves user', async () => {
const created = await repo.create({
email: '[email protected]',
name: 'Test'
});
const found = await repo.findById(created.id);
expect(found).toEqual(created);
});
});
```
---
## E2E Testing
### Playwright
```typescript
import { test, expect } from '@playwright/test';
test.describe('User Authentication', () => {
test('successful login flow', async ({ page }) => {
await page.goto('/login');
// Fill form
await page.fill('[data-testid="email-input"]', '[email protected]');
await page.fill('[data-testid="password-input"]', 'password123');
// Submit
await page.click('[data-testid="login-button"]');
// Verify redirect to dashboard
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('[data-testid="welcome-message"]'))
.toContainText('Welcome, [email protected]');
});
test('shows error for invalid credentials', async ({ page }) => {
await page.goto('/login');
await page.fill('[data-testid="email-input"]', '[email protected]');
await page.fill('[data-testid="password-input"]', 'wrongpassword');
await page.click('[data-testid="login-button"]');
await expect(page.locator('[data-testid="error-message"]'))
.toBeVisible()
.toContainText('Invalid credentials');
});
});
test.describe('Shopping Cart', () => {
test('add item and checkout', async ({ page }) => {
// Setup - login
await page.goto('/login');
await page.fill('[data-testid="email-input"]', '[email protected]');
await page.fill('[data-testid="password-input"]', 'password');
await page.click('[data-testid="login-button"]');
// Browse products
await page.goto('/products');
await page.click('[data-testid="product-1"] [data-testid="add-to-cart"]');
// Verify cart
await expect(page.locator('[data-testid="cart-count"]')).toHaveText('1');
// Checkout
await page.click('[data-testid="cart-icon"]');
await page.click('[data-testid="checkout-button"]');
// Fill shipping
await page.fill('[data-testid="address"]', '123 Test St');
await page.click('[data-testid="place-order"]');
// Verify success
await expect(page).toHaveURL(/\/orders\/\d+/);
await expect(page.locator('[data-testid="order-status"]'))
.toContainText('Order Confirmed');
});
});
```
### Visual Regression Testing
```typescript
import { test, expect } from '@playwright/test';
test('homepage visual regression', async ({ page }) => {
await page.goto('/');
// Wait for dynamic content
await page.waitForSelector('[data-testid="hero-section"]');
// TakRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.