Receber por email
← Voltar para o catálogo

api-testing

Use this skill when testing REST or GraphQL APIs, implementing contract tests, setting up mock servers, or validating API behavior. Triggers on API testing, Postman, contract testing, Pact, mock servers, MSW, HTTP assertions, response validation, and any task requiring API test automation.

185estrelas
Atualizado há 4 meses

Ver no GitHub ↗ Licença: MIT

Como adicionar

/plugin marketplace add AbsolutelySkilled/AbsolutelySkilled

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/api-testing-absolutelyskilled/svg)](https://www.skillteca.com.br/skills/api-testing-absolutelyskilled)

Skills relacionadas

Ver todas de Automação →

Alerta por categoria

Receba novas skills de Automação toda segunda

1 email curto, só com as skills novas de Automação. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

When this skill is activated, always start your first response with the 🧢 emoji.

API Testing

A comprehensive framework for testing REST and GraphQL APIs with confidence. Covers the full spectrum from unit-level handler tests to cross-service contract tests, with emphasis on what to test at each layer and why - not just syntax. Designed for engineers who can write tests but need opinionated guidance on strategy, tooling, and avoiding common traps.

When to use this skill

Trigger this skill when the user:

  • Writes tests for a REST or GraphQL API endpoint
  • Sets up integration or end-to-end tests for an HTTP service
  • Implements contract testing between a consumer and provider
  • Creates mock servers or stubs for downstream dependencies
  • Validates response schemas or payload shapes
  • Tests authentication flows (JWT, OAuth, API keys)
  • Tests error handling, edge cases, or failure scenarios
  • Asks about Supertest, Pact, MSW, Zod validation, or Apollo testing

Do NOT trigger this skill for:

  • UI/component testing concerns (use a frontend-testing skill instead)
  • Load/performance testing - that is a separate discipline with different tooling

Key principles

  1. Test behavior, not implementation - Assert on what the API returns to

callers, not on how internal functions are wired together. An endpoint test that reaches the router and asserts on status code + response body is worth ten unit tests on internal helpers.

  1. Isolate at the right boundary - Unit tests mock everything below the

handler. Integration tests use a real database (test container or in-memory). Contract tests verify only the interface promise. Choose the boundary that catches the most bugs with the least brittleness.

  1. Schema-first assertions - Validate response shape with a schema (Zod,

JSON Schema) rather than field-by-field assertions. One schema assertion catches structural regressions that 20 individual assertions would miss.

  1. Contracts are promises, not snapshots - A contract test verifies that a

provider will always satisfy what a consumer expects. It must be run on every deploy. A snapshot that drifts silently is worse than no test.

  1. Mock at the network boundary, not inside functions - Use MSW or nock to

intercept HTTP calls at the network layer. Mocking individual imported functions couples tests to implementation details and breaks on refactors.

Core concepts

API test types

| Type | What it tests | Scope | Speed | |---|---|---|---| | Unit | Handler logic, middleware, validators | Single function | Fast | | Integration | Full request cycle with real DB | Service in isolation | Medium | | Contract | Interface promise between consumer + provider | Two services | Medium | | End-to-end | Complete user journey across services | Full stack | Slow |

Default strategy: Integration tests for business logic (they give the most confidence per line of test code). Unit tests for pure transformation logic. Contract tests at service boundaries. E2E only for the critical happy path.

Mock vs stub vs fake

| Term | Definition | Use for | |---|---|---| | Mock | Records calls and verifies expectations | Verifying side effects (emails sent, events published) | | Stub | Returns canned responses without recording | Replacing slow/expensive dependencies | | Fake | Working implementation of a lighter version | In-memory DB, in-process message queue |

Prefer fakes over stubs over mocks. Mocks that verify call counts are fragile and break whenever you refactor internal wiring.

Schema validation

Validate response schemas at the integration test level. Use Zod because it:

  • Produces TypeScript types from the same definition (no duplication)
  • Gives precise error messages when assertions fail
  • Can be shared between test and production code for dual validation

Common tasks

Test REST endpoints with Supertest

Supertest binds directly to an Express/Fastify app without starting a real HTTP server. Use it for integration tests that exercise the full request pipeline.

// tests/users.test.ts
import request from 'supertest';
import { app } from '../src/app';
import { db } from '../src/db';

beforeEach(async () => {
  await db.migrate.latest();
  await db.seed.run();
});

afterEach(async () => {
  await db.migrate.rollback();
});

describe('GET /users/:id', () => {
  it('returns 200 with user data for a valid id', async () => {
    const res = await request(app)
      .get('/users/1')
      .set('Authorization', 'Bearer test-token')
      .expect(200);

    expect(res.body).toMatchObject({
      id: 1,
      email: expect.stringContaining('@'),
      createdAt: expect.any(String),
    });
  });

  it('returns 404 when user does not exist', async () => {
    const res = await request(app)
      .get('/users/99999')
      .set('Authorization', 'Bearer test-token')
      .expect(404);

    expect(res.body).toMatchObject({
      type: expect.stringContaining('not-found'),
      status: 404,
    });
  });

  it('returns 401 when no auth token is provided', async () => {
    await request(app).get('/users/1').expect(401);
  });
});

Test GraphQL APIs with Apollo Server Testing

Use @apollo/server test utilities to execute operations in-process. This avoids the overhead of HTTP while still exercising the full resolver chain.

// tests/graphql/users.test.ts
import { ApolloServer } from '@apollo/server';
import { typeDefs } from '../src/schema';
import { resolvers } from '../src/resolvers';
import { createTestContext } from './helpers/context';

let server: ApolloServer;

beforeAll(async () => {
  server = new ApolloServer({ typeDefs, resolvers });
  await server.start();
});

afterAll(async () => {
  await server.stop();
});

describe('Query.user', () => {
  it('returns user fields when authenticated', async () => {
    const { body } = await server.executeOperation(
      {
        query: `query GetUser($id: ID!) {
          user(id: $id) { id email createdAt }
        }`,
        variables: { id: '1' },
      },
      { contextValue: createTestContext({ userId: 'viewer-1' }) }
    );

    expect(body.kind).toBe('single');
    if (body.kind === 'single') {
      expect(body.singleResult.errors).toBeUndefined();
      expect(body.singleResult.data?.user).toMatchObject({
        id: '1',
        email: expect.any(String),
      });
    }
  });

  it('returns null for a user that does not exist', async () => {
    const { body } = await server.executeOperation(
      { query: `query { user(id: "nonexistent") { id } }` },
      { contextValue: createTestContext({ userId: 'viewer-1' }) }
    );

    if (body.kind === 'single') {
      expect(body.singleResult.data?.user).toBeNull();
    }
  });
});

Contract testing with Pact

For detailed Pact consumer and provider verification examples, see references/contract-and-auth-testing.md.

Mock APIs with MSW

MSW intercepts at the Service Worker level in browsers and at the network layer in Node.js. Use it to replace real API calls in tests without patching imports.

// tests/msw/handlers.ts
import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('https://api.example.com/users/:id', ({ params }) => {
    if (params.id === '404') {
      return HttpResponse.json({ type: 'not-found', status: 404 }, { status: 404 });
    }
    return HttpResponse.json({ id: params.id, email: 'test@example.com' });
  }),

  http.post('https://api.example.com/orders', async ({ request }) => {
    const body = await request.json();
    return HttpResponse.json({ id: 'order-1', ...body }, { status: 201 });
  }),
];

// tests/setup.ts
import { setupServer } from 'msw/node';
import { handlers } from './msw/handlers';

export const server = setupServer(...handlers);

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHa
Compartilhar X LinkedIn