Skip to content
Development
Command

/nextjs-api-tester

Test and validate Next.js API routes with comprehensive test scenarios

From plugin
claude-code-templates
30k200 skills200 agents200 commands2 MCP
Install
$ npx -y skills add davila7/claude-code-templates --agent claude-code

How it fires

How this command gets triggered: by you, by Claude, or both.

  • Fires itselfClaude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/nextjs-api-tester

Context preview

What this command does when you run it.

Test and validate Next.js API routes with comprehensive test scenarios

Command definition

nextjs-api-tester.md
allowed-tools: Read, Write, Edit, Bash
argument-hint: [route-path] [--method=GET] [--data='{}'] [--headers='{}']
description: Test and validate Next.js API routes with comprehensive test scenarios

Next.js API Route Tester

**API Route**: $ARGUMENTS

Current Project Analysis

API Routes Detection

  • App Router API: @app/api/
  • Pages Router API: @pages/api/
  • API configuration: @next.config.js
  • Environment variables: @.env.local

Project Context

  • Next.js version: !`grep '"next"' package.json | head -1`
  • TypeScript config: @tsconfig.json (if exists)
  • Testing framework: @jest.config.js or @vitest.config.js (if exists)

API Route Analysis

Route Discovery

Based on the provided route path, analyze:

  • **Route File**: Locate the actual route file
  • **HTTP Methods**: Supported methods (GET, POST, PUT, DELETE, PATCH)
  • **Route Parameters**: Dynamic segments and query parameters
  • **Middleware**: Applied middleware functions
  • **Authentication**: Required authentication/authorization

Route Implementation Review

  • Route handler implementation: @app/api/[route-path]/route.ts or @pages/api/[route-path].ts
  • Type definitions: @types/ or inline types
  • Validation schemas: @lib/validations/ or inline validation
  • Database models: @lib/models/ or @models/

Test Generation Strategy

1. Basic Functionality Tests

// Basic API route test template
describe('API Route: /api/[route-path]', () => {
  describe('GET requests', () => {
    test('should return 200 for valid request', async () => {
      const response = await fetch('/api/[route-path]');
      expect(response.status).toBe(200);
    });

    test('should return valid JSON response', async () => {
      const response = await fetch('/api/[route-path]');
      const data = await response.json();
      expect(data).toBeDefined();
      expect(typeof data).toBe('object');
    });
  });

  describe('POST requests', () => {
    test('should create resource with valid data', async () => {
      const testData = { name: 'Test', email: 'test@example.com' };
      const response = await fetch('/api/[route-path]', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(testData)
      });
      
      expect(response.status).toBe(201);
      const result = await response.json();
      expect(result.name).toBe(testData.name);
    });

    test('should reject invalid data', async () => {
      const invalidData = { invalid: 'field' };
      const response = await fetch('/api/[route-path]', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(invalidData)
      });
      
      expect(response.status).toBe(400);
    });
  });
});

2. Authentication Tests

describe('Authentication', () => {
  test('should require authentication for protected routes', async () => {
    const response = await fetch('/api/protected-route');
    expect(response.status).toBe(401);
  });

  test('should allow authenticated requests', async () => {
    const token = 'valid-jwt-token';
    const response = await fetch('/api/protected-route', {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    expect(response.status).not.toBe(401);
  });

  test('should validate JWT token format', async () => {
    const invalidToken = 'invalid-token';
    const response = await fetch('/api/protected-route', {
      headers: { 'Authorization': `Bearer ${invalidToken}` }
    });
    expect(response.status).toBe(403);
  });
});

3. Input Validation Tests

describe('Input Validation', () => {
  const validationTests = [
    { field: 'email', invalid: 'not-an-email', valid: 'test@example.com' },
    { field: 'phone', invalid: '123', valid: '+1234567890' },
    { field: 'age', invalid: -1, valid: 25 },
    { field: 'name', invalid: '', valid: 'John Doe' }
  ];

  validationTests.forEach(({ field, invalid, valid }) => {
    test(`should validate ${field} field`, async () => {
      const invalidData = { [field]: invalid };
      const validData = { [field]: valid };

      // Test invalid data
      const invalidResponse = await fetch('/api/[route-path]', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(invalidData)
      });
      expect(invalidResponse.status).toBe(400);

      // Test valid data
      const validResponse = await fetch('/api/[route-path]', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(validData)
      });
      expect(validResponse.status).not.toBe(400);
    });
  });
});

4. Error Handling Tests

describe('Error Handling', () => {
  test('should handle malformed JSON', async () => {
    const response = await fetch('/api/[route-path]', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: 'invalid-json'
    });
    expect(response.status).toBe(400);
  });

  test('should handle missing Content-Type header', async () => {
    const response = await fetch('/api/[route-path]', {
      method: 'POST',
      body: JSON.stringify({ test: 'data' })
    });
    expect(response.status).toBe(400);
  });

  test('should handle request timeout', async () => {
    // Mock slow endpoint
    jest.setTimeout(5000);
    const response = await fetch('/api/slow-endpoint');
    // Test appropriate timeout handling
  }, 5000);

  test('should handle database connection errors', async () => {
    // Mock database failure
    const mockDbError = jest.spyOn(db, 'connect').mockRejectedValue(new Error('DB Error'));
    
    const response = await fetch('/api/[route-path]');
    expect(response.status).toBe(500);
    
    mockDbError.mockRestore();
  });
});

5. Performance Tests

describe('Performance', () => {
  test('should respond within acceptable time', async () => {
    const startTi
Read more
Ships withclaude-code-templates

Ready-to-use configurations for Anthropic's Claude Code. A comprehensive collection of AI agents, custom commands, settings, hooks, external integrations (MCPs), and project templates to enhance your development workflow.

Get the whole plugin, auto-invoked
Stats
30,155
Stars
18
Views
3,377
Forks
Active
Maintenance
Python
Language
MIT
License
27m ago
Last commit
1y ago
Created

Repo: davila7/claude-code-templates