Chai OpenAPI Response Validator
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
-
TypeError: chaiResponseValidator is not a function
cause Attempting to use `chaiResponseValidator` in a CommonJS environment without accessing its `.default` property.fixChange `const chaiResponseValidator = require('chai-openapi-response-validator');` to `const chaiResponseValidator = require('chai-openapi-response-validator').default;` -
Expected response body to satisfy OpenAPI spec, but it had the following errors: ...
cause The HTTP response body or status code does not conform to the schema defined in your OpenAPI specification for the given endpoint and response code.fixReview the detailed error messages provided by the assertion failure to identify the specific validation discrepancy. Either update your API response to match the spec or update the OpenAPI spec to reflect the correct response structure. -
Invalid OpenAPI spec: Path '/your/path' not found
cause The `chaiResponseValidator` was initialized with an OpenAPI specification that does not contain the expected path or operation (`GET`, `POST`, etc.) being tested. This can also happen if the provided path is relative instead of absolute, or if the spec itself is malformed.fixEnsure the path and HTTP method in your test precisely match a defined path and method in your loaded OpenAPI specification. Verify the OpenAPI spec is correctly structured and accessible.
Warnings
- breaking The underlying `openapi-response-validator` dependency was updated from v3 to v9 in `chai-openapi-response-validator` v0.14.0. This change resulted in altered validation error messages and potentially subtle shifts in validation rules. Test assertions that relied on exact error message strings may break.
- gotcha When using CommonJS `require()`, directly importing `chai-openapi-response-validator` will result in `chaiResponseValidator` being an object containing the default export, not the function itself. This typically manifests as 'TypeError: chaiResponseValidator is not a function'.
- gotcha The `filepathOrObject` parameter for `chaiResponseValidator` can be an absolute path to a YAML/JSON file or a JavaScript object representing the OpenAPI spec. Ensure the path is correct and the file is accessible, or the object is a valid OpenAPI definition. An invalid spec will lead to initialization errors.
Install
-
npm install chai-openapi-response-validator -
yarn add chai-openapi-response-validator -
pnpm add chai-openapi-response-validator
Imports
- chaiResponseValidator
import chaiResponseValidator from 'chai-openapi-response-validator';
- chaiResponseValidator
const chaiResponseValidator = require('chai-openapi-response-validator');const chaiResponseValidator = require('chai-openapi-response-validator').default; - satisfyApiSpec
expect(response).to.satisfyApiSpec();
Quickstart
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;
// }
});
});