home / skills / yonatangross / orchestkit / integration-testing

integration-testing skill

/plugins/ork/skills/integration-testing

This skill accelerates integration testing across APIs and components, providing patterns for API, database, and UI testing with fast feedback.

npx playbooks add skill yonatangross/orchestkit --skill integration-testing

Review the files below or copy the command above to add this skill to your agents.

Files (4)
SKILL.md
4.0 KB
---
name: integration-testing
description: Integration testing patterns for APIs and components. Use when testing component interactions, API endpoints with test databases, or service layer integration.
tags: [testing, integration, api, database]
context: fork
agent: test-generator
version: 1.0.0
author: OrchestKit
user-invocable: false
---

# Integration Testing

Test how components work together.

## API Integration Test

```typescript
import { describe, test, expect } from 'vitest';
import request from 'supertest';
import { app } from '../app';

describe('POST /api/users', () => {
  test('creates user and returns 201', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ email: '[email protected]', name: 'Test' });

    expect(response.status).toBe(201);
    expect(response.body.id).toBeDefined();
    expect(response.body.email).toBe('[email protected]');
  });

  test('returns 400 for invalid email', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ email: 'invalid', name: 'Test' });

    expect(response.status).toBe(400);
    expect(response.body.error).toContain('email');
  });
});
```

## FastAPI Integration Test

```python
import pytest
from httpx import AsyncClient
from app.main import app

@pytest.fixture
async def client():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        yield ac

@pytest.mark.asyncio
async def test_create_user(client: AsyncClient):
    response = await client.post(
        "/api/users",
        json={"email": "[email protected]", "name": "Test"}
    )

    assert response.status_code == 201
    assert response.json()["email"] == "[email protected]"

@pytest.mark.asyncio
async def test_get_user_not_found(client: AsyncClient):
    response = await client.get("/api/users/nonexistent")

    assert response.status_code == 404
```

## Test Database Setup

```python
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

@pytest.fixture(scope="function")
def db_session():
    """Fresh database per test."""
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()

    yield session

    session.close()
    Base.metadata.drop_all(engine)
```

## React Component Integration

```typescript
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { QueryClientProvider } from '@tanstack/react-query';

test('form submits and shows success', async () => {
  const user = userEvent.setup();

  render(
    <QueryClientProvider client={queryClient}>
      <UserForm />
    </QueryClientProvider>
  );

  await user.type(screen.getByLabelText('Email'), '[email protected]');
  await user.click(screen.getByRole('button', { name: /submit/i }));

  expect(await screen.findByText(/success/i)).toBeInTheDocument();
});
```

## Coverage Targets

| Area | Target |
|------|--------|
| API endpoints | 70%+ |
| Service layer | 80%+ |
| Component interactions | 70%+ |

## Key Decisions

| Decision | Recommendation |
|----------|----------------|
| Database | In-memory SQLite or test container |
| Execution | < 1s per test |
| External APIs | MSW (frontend), VCR.py (backend) |
| Cleanup | Fresh state per test |

## Common Mistakes

- Shared test database state
- No transaction rollback
- Testing against production APIs
- Slow setup/teardown

## Related Skills

- `unit-testing` - Isolated tests
- `msw-mocking` - Network mocking
- `e2e-testing` - Full flow testing

## Capability Details

### api-testing
**Keywords:** api, endpoint, httpx, testclient
**Solves:**
- Test FastAPI endpoints
- Integration test patterns
- API contract testing

### database-testing
**Keywords:** database, fixture, transaction, rollback
**Solves:**
- Test database operations
- Use transaction rollback
- Create test fixtures

### test-plan-template
**Keywords:** plan, template, strategy, coverage
**Solves:**
- Integration test plan template
- Coverage strategy
- Test organization

Overview

This skill provides practical integration testing patterns for APIs, service layers, databases, and UI components. It collects concise examples, fixtures, and decisions to help teams write fast, reliable integration tests across TypeScript (Node/React) and Python (FastAPI) stacks. Use it to standardize test setup, coverage targets, and cleanup strategies for predictable CI runs.

How this skill works

The skill shows concrete test examples for API endpoints, FastAPI async clients, in-memory test databases, and React component interaction tests. It includes fixtures for fresh database state per test, recommendations for network mocking (MSW, VCR.py), and guidance on execution time and coverage targets. Follow the patterns to isolate integrations, ensure rollback/cleanup, and verify component-to-service interactions.

When to use it

  • Validating API endpoints with a test database or test client
  • Verifying service layer logic across modules rather than unit-only
  • Testing React components that depend on async data (React Query)
  • Running fast integration tests in CI with deterministic state
  • Replacing flaky external API calls with mocks or recorded responses

Best practices

  • Use a fresh in-memory database or test container per test to avoid state leakage
  • Keep each test under ~1s where possible and target fast setup/teardown
  • Mock external HTTP calls with MSW for frontend and VCR.py or recorded stubs for backend
  • Assert HTTP status and contract fields (id, email) not just implementation details
  • Aim for service layer and API coverage targets before expanding UI tests

Example use cases

  • POST /api/users endpoint: verify 201 on valid payload and 400 on invalid email
  • FastAPI async client tests for create and not-found scenarios using httpx AsyncClient
  • SQLite in-memory fixtures for isolated DB sessions with create/drop per test
  • React form integration: type into inputs, submit, and assert success message
  • Establishing CI thresholds: API 70%+, service 80%+, component interactions 70%+

FAQ

How do I avoid flaky tests when external APIs are involved?

Mock external calls—use MSW for frontend tests and VCR.py or recorded stubs for backend tests so tests run deterministically without reaching production services.

Should I use an in-memory DB or a test container?

Prefer in-memory SQLite for fast unit-level integration tests; use test containers when you need realistic behavior that matches production DB features.