Agent skill
api-tests
Create, repair, and extend NestJS API end-to-end tests using the repository's existing runner (Vitest/Jest) plus Supertest, with deterministic auth detection and JWT protected-route coverage when configured. Use when users ask to add controller endpoint e2e tests, fix failing API tests, add auth/login token scenarios, or improve API test reliability before CI/release.
Install this agent skill to your Project
npx add-skill https://github.com/majiayu000/claude-skill-registry/tree/main/skills/other/other/nestjs-api-tests
SKILL.md
NestJS API Tests (e2e)
Deterministic Workflow
- Inspect test setup first:
package.json,test/,vitest*.config.*,jest*.config.*, and e2e scripts. - Reuse the repository's existing e2e runner and conventions. Never introduce a second e2e runner.
- Identify target endpoints/controllers and map expected success plus failure behavior.
- Add or update
test/**/*.e2e-spec.tsfiles per feature/controller. - Mirror production bootstrap behavior from
src/main.tsfor all global HTTP-affecting configuration. - Detect whether JWT auth is configured using the rules in this file and reference.md.
- If JWT auth exists, add the full JWT scenario matrix.
- Run the project e2e command, fix failures, and report exact verification results.
Keep Existing Test Runner
- Reuse the repository's current test framework and config.
- Do not introduce a second e2e runner.
- Prefer one spec file per feature area:
test/auth.e2e-spec.tstest/users.e2e-spec.tstest/<feature>.e2e-spec.ts
Mirror Production App Bootstrap
Apply the same app-level behavior as src/main.ts so tests match runtime behavior. At minimum, mirror ValidationPipe options and all global middleware/interceptors/filters/guards that change HTTP behavior.
import { ValidationPipe } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { AppModule } from '../src/app.module';
let app: INestApplication;
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }));
await app.init();
Without this parity, DTO validation and status-code assertions can diverge from production.
Detect JWT/Auth Usage
Treat auth as configured when at least one condition is true:
JWT_SECRET(or equivalent token secret env key) is read by auth config/module code.- A login endpoint returns an access token (for example
POST /auth/login). - One or more routes use auth guards (
AuthGuard, passport guard, custom JWT guard).
If configured, include the JWT scenario matrix below.
JWT Scenario Matrix
Add all of the following when JWT auth exists:
- Valid login: send correct credentials, expect
200and token field (access_tokenor project equivalent). - Invalid login: send wrong credentials, expect
401. - Guarded route without token: expect
401. - Guarded route with valid token: login first, send
Authorization: Bearer <token>, expect success (200/204as applicable). - Guarded route with invalid or expired token: expect
401.
Token Handling Pattern
Use Supertest auth headers directly:
const loginRes = await request(app.getHttpServer())
.post('/auth/login')
.send({ username: 'admin', password: 'admin123' })
.expect(200);
const token = loginRes.body.access_token;
await request(app.getHttpServer())
.get('/users/me')
.set('Authorization', `Bearer ${token}`)
.expect(200);
If login response keys differ (for example token), assert the real key used by the project.
Environment and Data
- Ensure required auth env values exist for tests (
JWT_SECRET, related expiry settings, DB URL). - Use a dedicated test database when the app persists users/sessions.
- Run migrations (or schema push) before e2e when required by the stack.
- Use deterministic test credentials from seed/setup fixtures.
- Do not depend on external network calls in e2e tests unless the repository already requires and mocks/stabilizes them.
Test Lifecycle and Assertions
- Initialize app in
beforeAll(orbeforeEachif isolation requires it). - Always close app in
afterAll(orafterEach) to avoid hanging handles. - Assert both status code and response shape for each endpoint.
- Cover negative paths for validation and auth failures.
- Prefer deterministic seed/setup data over implicit ordering between tests.
Verification
- Run project e2e command (
npm run test:e2eor repository equivalent). - Ensure new tests pass with existing CI thresholds and lint rules.
- Keep tests stable (no hidden ordering dependencies, no real external calls).
- If tests are skipped or blocked, report the exact blocker and the next concrete command to unblock.
Additional Resources
- JWT detection rules and example snippets: reference.md
Recommended Agent Skills
Expand your agent's capabilities with these related and highly-rated skills.
agent-ops-spec
Manage specification documents in .agent/specs/. Use when user provides requirements, acceptance criteria, or feature descriptions that need to be tracked and validated against implementation.
agent-ops-state
Maintain .agent state files. Use at session start, after meaningful steps, and before concluding: read/update constitution/memory/focus/issues/baseline consistently.
agent-ops-spec
Manage specification documents in .agent/specs/. Use when user provides requirements, acceptance criteria, or feature descriptions that need to be tracked and validated against implementation.
agent-ops-testing
Test strategy, execution, and coverage analysis. Use when designing tests, running test suites, or analyzing test results beyond baseline checks.
agent-ops-testing
Test strategy, execution, and coverage analysis. Use when designing tests, running test suites, or analyzing test results beyond baseline checks.
agent-ops-state
Maintain .agent state files. Use at session start, after meaningful steps, and before concluding: read/update constitution/memory/focus/issues/baseline consistently.
Didn't find tool you were looking for?