Registry / testing / api-contract-validator

api-contract-validator

JSON →
library2.2.8jsnpmunverified

The `api-contract-validator` package provides a plugin for popular JavaScript assertion libraries like Chai, Should.js, and Jest, enabling validation of API response schemas against OpenAPI (Swagger) definitions. This tool facilitates contract testing by transforming an OpenAPI definition file (YAML or JSON) into a JSON schema, which is then used to validate incoming HTTP responses. The current stable version is 2.2.8, with releases appearing to be maintenance-focused, primarily consisting of dependency upgrades rather than new features or breaking changes. Key differentiators include its plug-and-play integration with existing testing frameworks, support for various HTTP client response formats (axios, superagent, supertest, request, light-my-request), comprehensive assertion failure messages, and the ability to generate coverage reports for API contracts. It supports OpenAPI 3.0 and can handle multiple definition files, making it suitable for larger, modular API landscapes.

npm install api-contract-validator
INSTALL
IMPORT
SIG · API-CONTRACT-VALID
A
api-contract-validator
testingjavascriptv2.2.8
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

chaiPlugin
import { chaiPlugin } from 'api-contract-validator';
const matchApiSchema = require('api-contract-validator').chaiPlugin;
While CommonJS `require` is shown in the README, modern Node.js and bundlers encourage ESM `import`. The package primarily exposes named exports for its plugins.
shouldPlugin
import { shouldPlugin } from 'api-contract-validator';
const matchApiSchema = require('api-contract-validator').shouldPlugin;
For Should.js integration, the `shouldPlugin` is exported as a named export. Ensure you import it correctly for ESM or destructure it from `require` for CJS.
jestPlugin
import { jestPlugin } from 'api-contract-validator';
const matchApiSchema = require('api-contract-validator').jestPlugin;
The `jestPlugin` registers custom matchers like `toMatchApiSchema` and `toHaveStatus`. It's crucial to call this imported function with your API definition path.
ApiContractValidator
import { ApiContractValidator } from 'api-contract-validator';
While less common for direct use, the underlying `ApiContractValidator` class can be imported if you need to instantiate the validator directly without framework-specific plugins.

This quickstart demonstrates how to integrate `api-contract-validator` with Chai and Supertest to validate an Express.js API's responses against an OpenAPI specification. It sets up a basic server, defines an OpenAPI schema (conceptually, for a `/pet/{id}` endpoint), and then uses the `matchApiSchema` assertion to verify that a successful API response conforms to the defined contract. It illustrates both the setup and a basic test case for a GET request.

import { chaiPlugin } from 'api-contract-validator'; import path from 'path'; import { expect, use } from 'chai'; import supertest from 'supertest'; // Assuming a simple Express app for demonstration const express = require('express'); const app = express(); app.get('/pet/:id', (req, res) => { const id = parseInt(req.params.id, 10); if (id === 123) { res.status(200).json({ id: 123, name: 'Fido', species: 'Dog' }); } else { res.status(404).json({ message: 'Pet not found' }); } }); // API definitions path (assuming myApp.yaml exists relative to this file) const apiDefinitionsPath = path.join(__dirname, 'myApp.yaml'); // add as chai plugin use(chaiPlugin({ apiDefinitionsPath })); const request = supertest(app); describe('Pet API Contract', () => { it('GET /pet/123 should match API schema', async () => { // A dummy myApp.yaml for the quickstart // paths: // /pet/{id}: // get: // parameters: // - in: path // name: id // schema: // type: integer // required: true // responses: // '200': // description: Successful response // content: // application/json: // schema: // type: object // properties: // id: // type: integer // name: // type: string // species: // type: string // required: // - id // - name // - species const response = await request.get('/pet/123'); expect(response).to.have.status(200).and.to.matchApiSchema(); }); it('GET /pet/456 should not match API schema (e.g., 404 response)', async () => { const response = await request.get('/pet/456'); expect(response).to.have.status(404); // The validator would still check if the 404 response schema exists // but in this quickstart, we're just checking the status. // expect(response).to.matchApiSchema(); }); });
Debug
Known issues
gotchaThe package relies on an external OpenAPI/Swagger definition file. Errors in the definition file (e.g., invalid YAML/JSON, incorrect paths/methods) will lead to validation failures or unexpected behavior during test execution, but these errors stem from the definition, not the validator itself. Ensure your API definition is valid and accurate.
fix
Use an OpenAPI linter or validator tool (e.g., `spectral`, `swagger-parser`) to pre-validate your API definition files before running tests with `api-contract-validator`.
affects: >=1.0.0
gotchaThis library is designed to work with specific HTTP response object structures from libraries like `axios`, `superagent`, `supertest`, and `request`. If you are using a custom HTTP client or a different library, you might need to manually construct an object with `path`, `method`, `status`, `body`, and `headers` properties to pass to `matchApiSchema`.
fix
Refer to the `README` for an example of manually passing the response object. Ensure the `path`, `method`, `status`, `body`, and `headers` fields accurately reflect the API call and its response.
affects: >=1.0.0
gotchaThe `api-contract-validator` package uses `api-schema-builder` internally. Frequent updates to `api-schema-builder` (as seen in recent `api-contract-validator` patch releases) suggest ongoing maintenance and potential internal changes that could subtly affect schema interpretation, although typically without breaking the public API.
fix
Regularly update `api-contract-validator` to benefit from the latest `api-schema-builder` fixes and improvements. Thoroughly test your contract validations after significant dependency bumps.
affects: >=2.0.0
Errors
Common errors & fixes
Error: definition not found for path: /api/v1/resource, method: get, status: 200
The API definition file provided to the validator does not contain an entry for the specified path, method, and status code combination.
fix
Verify that your `apiDefinitionsPath` correctly points to your OpenAPI/Swagger file and that the file includes the definition for `GET /api/v1/resource` with a `200` response schema. Check for typos in path or method.
AssertionError: expected { Object (status, body, ...) } to match API schema
The actual API response body or headers do not conform to the JSON schema generated from your OpenAPI definition for the given endpoint and status code.
fix
Examine the detailed assertion failure message (usually provided by Chai/Jest). Compare the actual response structure and data types against your OpenAPI definition's `schema` for the relevant response. This often indicates a mismatch between API implementation and its documentation.
YAMLException: YAMLException: bad indentation of a mapping entry at line X, column Y
The OpenAPI definition file (if YAML) has a syntax error, specifically incorrect indentation or formatting, preventing `api-schema-builder` from parsing it.
fix
Review the specified line and column in your YAML definition file. Use a YAML linter or editor with YAML validation to correct indentation and syntax errors.
Upgrade
Version history
2.2.8latest on npm
Audit
Dependencies
api-schema-builderrequiredCore dependency for transforming API definitions into JSON schemas for validation. This package is frequently updated as seen in recent release notes.
chaioptionalPeer dependency when using the `chaiPlugin` for assertion chaining. Not directly required for the package's core logic but essential for its primary use case.
shouldoptionalPeer dependency when using the `shouldPlugin` for assertion chaining. Similar to Chai, it's optional but critical for its intended integration.
jestoptionalPeer dependency when using the `jestPlugin` for custom matchers. Optional but necessary for Jest test environments.
Agent activity
32 hits · last 30 days
node
26
OpenAI (training)
3
Resources
api-contract-validator — npm install api-contract-validator · libregistry