Chai OpenAPI Response Validator

0.14.2 · active · verified Wed Apr 22

Chai OpenAPI Response Validator is a testing utility that extends the Chai assertion library, enabling developers to validate HTTP responses and arbitrary JavaScript objects against an OpenAPI (Swagger) specification. The current stable version is 0.14.2, released in January 2022. While it doesn't adhere to a strict release cadence, the project shows active maintenance with several releases in late 2021 and early 2022. Key differentiators include its seamless integration with Chai's assertion syntax (e.g., `expect(response).to.satisfyApiSpec`), support for both OpenAPI 2 and 3 specifications in YAML or JSON formats, and robust handling of `$ref` definitions. It is compatible with various HTTP clients like Axios, `request-promise`, Supertest, Superagent, and `chai-http`, making it versatile for different testing setups, including Mocha. It also provides immediate feedback if the loaded OpenAPI specification itself is invalid.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up Chai with `chai-openapi-response-validator`, load a simple OpenAPI specification directly as an object, and then assert that a mock HTTP response (or an actual one from Axios) satisfies the defined API specification.

import chai from 'chai';
import chaiResponseValidator from 'chai-openapi-response-validator';
import axios from 'axios';

const expect = chai.expect;

// Load your OpenAPI file (YAML or JSON) into the plugin
// In a real app, use an actual path or load from an environment variable
chai.use(chaiResponseValidator({
  openapi: '3.0.0',
  info: { title: 'Example API', version: '1.0.0' },
  paths: {
    '/example': {
      get: {
        responses: {
          200: {
            description: 'A successful response',
            content: {
              'application/json': {
                schema: {
                  type: 'object',
                  properties: {
                    message: { type: 'string' }
                  },
                  required: ['message']
                }
              }
            }
          }
        }
      }
    }
  }
}));

describe('GET /example', () => {
  it('should satisfy OpenAPI spec', async () => {
    // Simulate an HTTP response (e.g., from an actual API call)
    const mockResponse = {
      status: 200,
      data: { message: 'Hello from API' },
      headers: { 'content-type': 'application/json' }
    };

    // Use Chai to assert that the mock response satisfies the OpenAPI spec
    expect(mockResponse).to.satisfyApiSpec();

    // Example with an actual axios call (if your server is running)
    // try {
    //   const res = await axios.get('http://localhost:3000/example');
    //   expect(res).to.satisfyApiSpec();
    // } catch (error) {
    //   console.error('Axios request failed:', error.message);
    //   throw error;
    // }
  });
});

view raw JSON →