npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@foryourdev/jest-swag

v2.0.1

Published

Generate OpenAPI/Swagger documentation from your Jest API tests

Readme

jest-swag

Generate OpenAPI/Swagger documentation directly from your Jest API tests! Inspired by rswag, jest-swag brings the same powerful concept to the JavaScript/TypeScript ecosystem.

🚀 Features

  • API-First Testing: Write Jest tests that double as API documentation
  • OpenAPI 3.0 Support: Generate standards-compliant OpenAPI specifications
  • Automatic Documentation: Documentation stays in sync with your tests
  • Swagger UI Integration: Interactive API documentation out of the box
  • TypeScript Support: Fully typed for better developer experience
  • Zero Configuration: Works with minimal setup

📦 Installation

npm install @foryourdev/jest-swag --save-dev

🚀 Framework Integration

Express.js Project

  1. Install jest-swag in your Express project:
cd your-express-project
npm install @foryourdev/jest-swag --save-dev
  1. Setup Swagger UI in your Express app:
// app.js or server.js
import express from 'express';
import { setupSwagger } from '@foryourdev/jest-swag';

const app = express();

// Only in development environment
if (process.env.NODE_ENV !== 'production') {
  setupSwagger(app, {
    routePrefix: '/api-docs',
    title: 'My API Documentation',
  });
}

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
  console.log('API docs available at http://localhost:3000/api-docs');
});
  1. Create API tests:
// tests/api/users.test.ts
import {
  path,
  get,
  post,
  tags,
  parameter,
  requestBody,
  response,
  jsonContent,
  schemas,
} from '@foryourdev/jest-swag';
import request from 'supertest';
import app from '../app';

describe('Users API', () => {
  path('/api/users', () => {
    get('Get all users', () => {
      tags('Users');

      parameter({
        name: 'page',
        in: 'query',
        description: 'Page number',
        required: false,
        schema: schemas.integer(1),
      });

      response(200, 'Users retrieved successfully', () => {
        return request(app).get('/api/users?page=1').expect(200);
      });
    });
  });
});
  1. Configure Jest to generate docs:
// jest.config.js
module.exports = {
  testEnvironment: 'node',
  reporters: [
    'default',
    [
      '@foryourdev/jest-swag/dist/reporter.js',
      {
        title: 'My Express API',
        version: '1.0.0',
        outputPath: './docs/openapi.json',
      },
    ],
  ],
};
  1. Run tests and access Swagger UI:
# Run tests to generate documentation
npm test

# Start your Express server
npm start

# Access Swagger UI at http://localhost:3000/api-docs

NestJS Project

  1. Install jest-swag:
cd your-nestjs-project
npm install @foryourdev/jest-swag --save-dev
  1. Setup JestSwag module in your NestJS app:
// app.module.ts
import { Module } from '@nestjs/common';
import { JestSwagModule } from '@foryourdev/jest-swag';

@Module({
  imports: [
    // Only in development
    ...(process.env.NODE_ENV !== 'production'
      ? [
          JestSwagModule.forRoot({
            path: 'api-docs',
            title: 'My NestJS API Documentation',
          }),
        ]
      : []),
    // ... other imports
  ],
})
export class AppModule {}
  1. Create NestJS API tests:
// test/users.e2e-spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
import {
  path,
  get,
  post,
  tags,
  parameter,
  requestBody,
  response,
  jsonContent,
  schemas,
} from '@foryourdev/jest-swag';

describe('Users (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  path('/users', () => {
    get('Get all users', () => {
      tags('Users');

      response(200, 'Success', () => {
        return request(app.getHttpServer()).get('/users').expect(200);
      });
    });

    post('Create user', () => {
      tags('Users');

      requestBody({
        required: true,
        content: jsonContent(
          schemas.object(
            {
              name: schemas.string('John Doe'),
              email: schemas.string('[email protected]'),
            },
            ['name', 'email'],
          ),
        ),
      });

      response(201, 'User created', () => {
        return request(app.getHttpServer())
          .post('/users')
          .send({ name: 'John', email: '[email protected]' })
          .expect(201);
      });
    });
  });

  afterAll(async () => {
    await app.close();
  });
});
  1. Configure Jest:
// jest.config.js
module.exports = {
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: 'test',
  testEnvironment: 'node',
  testRegex: '.*\\.spec\\.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  reporters: [
    'default',
    [
      '@foryourdev/jest-swag/dist/reporter.js',
      {
        title: 'My NestJS API',
        version: '1.0.0',
        outputPath: './docs/openapi.json',
        servers: [
          { url: 'http://localhost:3000', description: 'Development server' },
        ],
      },
    ],
  ],
};
  1. Run tests and access Swagger UI:
# Run e2e tests to generate documentation
npm run test:e2e

# Start your NestJS application
npm start

# Access Swagger UI at http://localhost:3000/api-docs

🎯 Quick Start

1. Write API tests using jest-swag DSL

// tests/api/users.test.ts
import {
  path,
  get,
  post,
  tags,
  parameter,
  requestBody,
  response,
  jsonContent,
  schemas,
} from '@foryourdev/jest-swag';

describe('Users API', () => {
  path('/users', () => {
    get('Get all users', () => {
      tags('Users');

      parameter({
        name: 'limit',
        in: 'query',
        description: 'Maximum number of users to return',
        required: false,
        schema: schemas.integer(10),
      });

      response(200, 'Successfully retrieved users', () => {
        // Your actual test logic here
        // expect(response.status).toBe(200);
      });

      response(400, 'Bad request');
    });

    post('Create user', () => {
      tags('Users');

      requestBody({
        description: 'User data',
        required: true,
        content: jsonContent(
          schemas.object(
            {
              name: schemas.string('John Doe'),
              email: schemas.string('[email protected]'),
              age: schemas.integer(30),
            },
            ['name', 'email'],
          ),
        ),
      });

      response(201, 'User created successfully', () => {
        // Your test logic
      });
    });
  });
});

2. Configure Jest Reporter

Add jest-swag reporter to your Jest configuration:

// jest.config.js
module.exports = {
  // ... other Jest configuration
  reporters: [
    'default',
    [
      'jest-swag/dist/reporter.js',
      {
        title: 'My API Documentation',
        version: '1.0.0',
        description: 'Generated API documentation',
        outputPath: './docs/openapi.json',
        servers: [
          { url: 'http://localhost:3000', description: 'Development server' },
          { url: 'https://api.example.com', description: 'Production server' },
        ],
      },
    ],
  ],
};

3. Run tests to generate documentation

# Generate documentation while running tests
npm test

# Or run tests specifically for documentation
npm run test:docs

# Start your app server (Express/NestJS)
npm start

4. Access Swagger UI directly in your app

After running tests and starting your server:

  • Express: http://localhost:3000/api-docs
  • NestJS: http://localhost:3000/api-docs
  • Files: docs/openapi.json, docs/openapi.yaml

No need for separate servers! 🎉 Swagger UI is integrated directly into your application.

📚 API Reference

Path Operations

import { path, get, post, put, patch, del } from '@foryourdev/jest-swag';

path('/users', () => {
  get('Get users', () => {
    /* ... */
  });
  post('Create user', () => {
    /* ... */
  });
  put('Update user', () => {
    /* ... */
  });
  patch('Patch user', () => {
    /* ... */
  });
  del('Delete user', () => {
    /* ... */
  });
});

Parameters

import { parameter, schemas } from '@foryourdev/jest-swag';

parameter({
  name: 'userId',
  in: 'path',
  description: 'User ID',
  required: true,
  schema: schemas.string(),
});

parameter({
  name: 'limit',
  in: 'query',
  schema: schemas.integer(10),
});

Request Bodies

import { requestBody, jsonContent, schemas } from '@foryourdev/jest-swag';

requestBody({
  description: 'User data',
  required: true,
  content: jsonContent(
    schemas.object(
      {
        name: schemas.string(),
        email: schemas.string(),
      },
      ['name', 'email'],
    ),
  ),
});

Response Definitions

import { response } from '@foryourdev/jest-swag';

response(200, 'Success', () => {
  // Your test assertions here
  expect(result.status).toBe(200);
});

response(404, 'Not found');
response(500, 'Internal server error');

Schema Helpers

import { schemas } from '@foryourdev/jest-swag';

// Basic types
schemas.string('example');
schemas.number(42);
schemas.integer(10);
schemas.boolean(true);

// Complex types
schemas.array(schemas.string(), ['item1', 'item2']);
schemas.object(
  {
    id: schemas.string(),
    name: schemas.string(),
  },
  ['id'],
  { id: '123', name: 'John' },
);

⚙️ Configuration

Jest Configuration

Add to your jest.config.js:

module.exports = {
  // ... other config
  reporters: [
    'default',
    [
      '@foryourdev/jest-swag/dist/reporter.js',
      {
        title: 'My API Documentation',
        version: '1.0.0',
        description: 'Generated API documentation',
        outputPath: './api-docs/openapi.json',
        servers: [
          { url: 'http://localhost:3000', description: 'Development server' },
          { url: 'https://api.example.com', description: 'Production server' },
        ],
      },
    ],
  ],
};

CLI Usage

# Generate documentation from saved specs
npx @foryourdev/jest-swag generate --title "My API" --version "2.0.0" --output ./docs/api.json

# Serve documentation
npx @foryourdev/jest-swag serve --port 3001 --docs ./docs

# Generate with config file
npx @foryourdev/jest-swag generate --config ./jest-swag.config.json

📄 Configuration File

Create jest-swag.config.json:

{
  "title": "My API Documentation",
  "version": "1.0.0",
  "description": "Comprehensive API documentation",
  "outputPath": "./docs/openapi.json",
  "servers": [
    {
      "url": "http://localhost:3000",
      "description": "Development server"
    },
    {
      "url": "https://api.example.com",
      "description": "Production server"
    }
  ]
}

🛠️ Scripts

Add these scripts to your package.json:

{
  "scripts": {
    "test": "jest --reporters=default --reporters=@foryourdev/jest-swag/dist/reporter.js",
    "test:docs": "jest --reporters=@foryourdev/jest-swag/dist/reporter.js",
    "docs:generate": "@foryourdev/jest-swag generate",
    "docs:serve": "@foryourdev/jest-swag serve"
  }
}

🤝 Comparison with rswag

| Feature | jest-swag | rswag | | ----------------- | --------------------- | ----------- | | Language | JavaScript/TypeScript | Ruby | | Test Framework | Jest | RSpec | | API Specification | OpenAPI 3.0 | OpenAPI 3.0 | | Documentation UI | Swagger UI | Swagger UI | | Auto-generation | ✅ | ✅ | | Type Safety | ✅ (TypeScript) | ✅ (Ruby) |

💡 Examples

Check out the test/example-api.test.ts file for comprehensive examples of:

  • User management API
  • Blog posts API
  • Complex request/response schemas
  • Parameter validation
  • Error handling

jest-swag - Because your API tests deserve some swag! 😎