testing-patterns
/testing-patterns
Prowadzi pisanie skutecznych testów w całym stosie: jednostkowych, integracyjnych, E2E i regresji wizualnej, z filozofią testowania, doborem frameworka, mockowaniem i integracją z CI.
- Autor
- organvm-iv-taxis ↗
- Repozytorium
- a-i--skills ↗
- Licencja
- Apache-2.0
- Ostatnia zmiana repozytorium
- 24.10.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 5
- Skrypty
- 0
- Komentarze HTML
- 1
- Adresy URL w SKILL.md
- 0
Brak sygnałów. Repozytorium zmienione 24.10.2026, bez odwołań do wycofanych modeli i API.
Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.
- SKILL.md zawiera komentarze HTML (1). Nie widać ich w podglądzie Markdown, a model je czyta.
Co robi i kiedy
Prowadzi pisanie skutecznych testów w całym stosie: jednostkowych, integracyjnych, E2E i regresji wizualnej, z filozofią testowania, doborem frameworka, mockowaniem i integracją z CI.
Oryginalny opis (EN)
Write effective tests across the stack—unit, integration, E2E, and visual regression. Covers testing philosophy, framework selection, mocking strategies, and CI integration. Triggers on testing, test coverage, TDD, or quality assurance requests.
Jak działa
- Testing Philosophy
- Unit Testing
- React Component Testing
- Integration Testing
- E2E Testing
- Mocking Strategies
- Test Configuration
- Coverage Strategy
- CI Integration
- Related Skills
Podgląd SKILL.md
---
name: testing-patterns
description: Write effective tests across the stack—unit, integration, E2E, and visual regression. Covers testing philosophy, framework selection, mocking strategies, and CI integration. Triggers on testing, test coverage, TDD, or quality assurance requests.
license: MIT
complexity: beginner
time_to_learn: 30min
tags:
- testing
- unit-tests
- integration-tests
- e2e
- vitest
- playwright
- mocking
governance_phases: [prove]
governance_norm_group: quality-gate
organ_affinity: [all]
triggers: [user-asks-about-testing, project-has-jest-config-js, project-has-pytest-ini, file-type:*.test.*, context:testing]
complements: [tdd-workflow, verification-loop]
---
# Testing Patterns
Build confidence through strategic testing.
## Testing Philosophy
### The Testing Trophy
```
╱╲
╱ ╲ E2E (few)
╱────╲
╱ ╲ Integration (more)
╱────────╲
╱ ╲ Unit (many, fast)
╱────────────╲
╱ Static ╲ TypeScript, ESLint
╱────────────────╲
```
### What to Test
| Test Type | What | Why |
|-----------|------|-----|
| Static | Types, lint rules | Catch errors at write-time |
| Unit | Pure functions, utils | Fast, precise feedback |
| Integration | Component + dependencies | Test contracts |
| E2E | User flows | Confidence in real usage |
### What NOT to Test
- Implementation details (internal state, private methods)
- Third-party library internals
- Constants and configuration
- Framework code
---
## Unit Testing
### Structure: AAA Pattern
```typescript
describe('calculateTotal', () => {
it('should apply discount to subtotal', () => {
// Arrange
const items = [{ price: 100 }, { price: 50 }];
const discount = 0.1;
// Act
const result = calculateTotal(items, discount);
// Assert
expect(result).toBe(135);
});
});
```
### Test Naming
```typescript
// Pattern: should [expected behavior] when [condition]
it('should return empty array when input is null')
it('should throw error when user is not authenticated')
it('should apply discount when coupon is valid')
```
### Testing Pure Functions
```typescript
// utils/format.ts
export function formatCurrency(cents: number): string {
return `$${(cents / 100).toFixed(2)}`;
}
// utils/format.test.ts
describe('formatCurrency', () => {
it('should format cents to dollar string', () => {
expect(formatCurrency(1000)).toBe('$10.00');
expect(formatCurrency(1)).toBe('$0.01');
expect(formatCurrency(0)).toBe('$0.00');
});
it('should handle negative values', () => {
expect(formatCurrency(-500)).toBe('$-5.00');
});
});
```
### Edge Cases to Consider
- Empty/null/undefined inputs
- Boundary values (0, -1, MAX_INT)
- Empty arrays/objects
- Invalid types (if not using TypeScript)
- Async edge cases (race conditions, timeouts)
---
## React Component Testing
### Testing Library Philosophy
> "The more your tests resemble the way your software is used, the more confidence they can give you."
### Component Test Structure
```tsx
import { render, screen, fireEvent } from '@testing-library/react';
import { Counter } from './Counter';
describe('Counter', () => {
it('should increment count when button clicked', async () => {
render(<Counter initialCount={0} />);
const button = screen.getByRole('button', { name: /increment/i });
await fireEvent.click(button);
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
});
```
### Query Priority
Use queries in this order (most to least preferred):
1. `getByRole` - Accessible to everyone
2. `getByLabelText` - Form fields
3. `getByPlaceholderText` - If no label
4. `getByText` - Non-interactive content
5. `getByTestId` - Last resort
### Async Testing
```tsx
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
it('should load data after button click', async () => {
const user = userEvent.setup();
render(<DataLoader />);
await user.click(screen.getByRole('button', { name: /load/i }));
// Wait for async content
await waitFor(() => {
expect(screen.getByText('Data loaded')).toBeInTheDocument();
});
});
```
### Mocking
```tsx
// Mock a module
vi.mock('./api', () => ({
fetchUser: vi.fn(() => Promise.resolve({ name: 'Test User' })),
}));
// Mock a hook
vi.mock('./useAuth', () => ({
useAuth: () => ({ user: { id: '1' }, isLoading: false }),
}));
// Mock fetch
global.fetch = vi.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ data: 'test' }),
})
);
```
---
## Integration Testing
### API Route Testing
```typescript
import { createMocks } from 'node-mocks-http';
import handler from './api/posts';
describe('/api/posts', () => {
it('should return posts list', async () => {
const { req, res } = createMocks({
method: 'GET',
});
await handler(req, res);
expect(res._getStatusCode()).toBe(200);
expect(JSON.parse(res._getData())).toHaveLength(3);
});
});
```
### Database Integration
```typescript
import { db } from '@/lib/db';
describe('User service', () => {
beforeEach(async () => {
await db.user.deleteMany(); // Clean state
});
afterAll(async () => {
await db.$disconnect();
});
it('should create user with valid data', async () => {
const user = await createUser({
email: 'test@example.com',
name: 'Test User'
});
expect(user.id).toBeDefined();
expect(user.email).toBe('test@example.com');
});
});
```
---
## E2E Testing
### Playwright Setup
```typescript
// e2e/auth.spec.ts
import { test, expect } from '@playwright/test';
test.describe('Authentication', () => {
test('should allow user to sign in', async ({ page }) => {
await page.goto('/login');
await page.fill('[name="email"]', 'user@example.com');
await page.fill('[name="password"]', 'password123');
await page.click('button[type="submit"]');
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('h1')).toContainText('Welcome');
});
});
```
### Page Object Pattern
```typescript
// e2e/pages/login.page.ts
export class LoginPage {
constructor(private page: Page) {}
async goto() {
await this.page.goto('/login');
}
async login(email: string, password: string) { <!-- allow-secret -->
await this.page.fill('[name="email"]', email);
await this.page.fill('[name="password"]', password);
await this.page.click('button[type="submit"]');
}
}
// e2e/auth.spec.ts
test('should login successfully', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('user@example.com', 'password');
await expect(page).toHaveURL('/dashboard');
});
```
### Visual Regression
```typescript
test('homepage should match snapshot', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveScreenshot('homepage.png');
});
```
---
## Mocking Strategies
### When to Mock
| Mock | When |
|------|------|
| External APIs | Always in unit/integration |
| Database | Sometimes (test containers vs mocks) |
| Time/Date | When testing time-dependent logic |
| Randomness | When testing deterministic output |
| Network | Always in unit tests |
### MSW (Mock Service Worker)
```typescript
// mocks/handlers.ts
import { rest } from 'msw';
export const handlers = [
rest.get('/api/users', (req, res, ctx) => {
return res(
ctx.json([
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
])
);
}),
rest.post('/api/users', async (req, res, ctx) => {
const body = await req.json();
return res(ctx.status(201), ctx.json({ id: 3, ...body }));
}),
];
```
---
## Test Configuration
### Vitest Config
```typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['./test/setup.ts'],
coverage: {
reporter: ['text', 'html'],
exclude: ['node_modules/', 'test/'],
},
},
});
```
### Test Setup
```typescript
// test/setup.ts
import '@testing-library/jest-dom';
import { server } from './mocks/server';
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
```
---
## Coverage Strategy
### Meaningful Coverage
| Type | Target | Notes |
|------|--------|-------|
| Statements | 70-80% | Don't chase 100% |
| Branches | 70-80% | Test important paths |
| Functions | 80%+ | All public APIs |
| Lines | 70-80% | Balance with velocity |
### What High Coverage Doesn't Mean
- Tests are good
- No bugs
- Code is maintainable
- Edge cases are covered
---
## CI Integration
```yaml
# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm run test:coverage
- uses: codecov/codecov-action@v3
with:
files: ./coverage/lcov.info
```
---
---
## Related Skills
### Complementary Skills (Use Together)
- **[tdd-workflow](../tdd-workflow/)** - Test-driven development workflow; combine with testing-patterns for complete TDD practice
- **[verification-loop](../verification-loop/)** - Iterative verification process that uses tests as quality gates
- **[deployment-cicd](../deployment-cicd/)** - CI/CD integration for running tests in pipelines
### Alternative Skills (Similar Purpose)
- **[webapp-testing](../webapp-testing/)** - Specialized web application testing with browser automation focus
### Prerequisite Skills (Learn First)
- None required - this is a foundational skill
---
## References
- `references/vitest-patterns.md` - Vitest specific patterns
- `references/playwright-patterns.md` - E2E testing patterns
- `references/mock-examples.md` - Mocking recipes
Pliki w paczce (5)
- SKILL.md 10 KB
- references/mock-examples.md 6 KB
- references/playwright-patterns.md 7 KB
- references/testing-strategies.md 7 KB
- references/vitest-patterns.md 6 KB
Wersje
| Repozytorium | Wynik | Licencja |
|---|---|---|
| Ta strona · organvm-iv-taxis/a-i--skills | 100 | Apache-2.0 |
| Reprograme/redevkit | 100 | MIT |
| piomin/claude-ai-spring-boot | 100 | Apache-2.0 |
| FrancoStino/opencode-skills-collection | 100 | MIT |
| rootcastleco/rei-skills | 100 | MIT |
| davila7/claude-code-templates | 100 | MIT |
| svngoku/coding-agents-skills | 100 | MIT |
| leather-io/mono | 100 | MIT |
| seandkendall/kiro-config | 100 | Apache-2.0 |
Identyczna treść występuje jeszcze w 4 innych folderach na GitHubie. Tu pokazujemy jedną, najlepiej ocenioną kopię.
Migawka bazy z 13.11.2026 · wersja paczki 65dcf4fb1ee7 (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 0 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 100python-testing-patterns
Stosuje wzorce testowania Python z pytest, mockowaniem i testami właściwości, przy testach jednostkowych, integracyjnych i programowaniu sterowanym testami. - 100testing-strategy
Opisuje strategie testowania testów jednostkowych, integracyjnych i end-to-end: piramida testów, strategie mockowania i wytyczne dotyczące pokrycia. - 95testing-builder
Generuje zestawy testów jednostkowych, integracyjnych i E2E na podstawie kodu i dotychczasowych wzorców testowania, także jako testy regresji po naprawie błędów. - 95testing-fundamentals
Prowadzi przez strategię testów jednostkowych, integracyjnych i E2E z Vitest, Jest i Playwright, z piramidą testów, wzorcem AAA, mockowaniem i pokryciem. - 100testing-best-practices
Opisuje zasady testów jednostkowych, integracyjnych i test-driven development przy pisaniu testów, przeglądzie kodu testowego, zwiększaniu pokrycia i ustalaniu strategii testowania. - 95test-specialist
Podaje wzorce pisania testów dla JS i TS, Pythona, Go i Rusta: jednostkowych, integracyjnych, E2E i regresji wizualnej, gdy użytkownik wprost prosi o testy lub pokrycie.