{"id":17722,"library":"jest-openapi","title":"Jest Matchers for OpenAPI Validation","description":"jest-openapi is a Jest plugin that significantly enhances the standard Jest assertion capabilities by providing specialized matchers for validating API responses and data objects against an OpenAPI specification (supporting both v2 and v3). Its core purpose is to automate the verification that a server's actual runtime behavior precisely matches its documented API contract. The current stable version, 0.14.2, was last updated in January 2022, having seen several iterative improvements and fixes throughout 2021, indicating an actively maintained project with a practical, feature-driven release cadence. This library is indispensable for ensuring contract consistency and preventing silent discrepancies between backend service implementations and their public-facing documentation, thereby reducing integration issues for consuming clients. It stands out by offering broad compatibility with responses from various popular HTTP client libraries, including axios, request-promise, supertest, and superagent. Furthermore, it effortlessly processes OpenAPI specifications provided in either YAML or JSON formats, intelligently resolves $ref declarations within the spec, and delivers clear, diagnostic error messages when validation failures occur. For development teams utilizing testing frameworks that are built around Chai, a companion package, chai-openapi-response-validator, offers an equivalent set of validation utilities.","status":"active","version":"0.14.2","language":"javascript","source_language":"en","source_url":"https://github.com/openapi-library/OpenAPIValidators/tree/master/packages/jest-openapi","tags":["javascript","jest","openapi","testing","response","validate","assertions","typescript"],"install":[{"cmd":"npm install jest-openapi","lang":"bash","label":"npm"},{"cmd":"yarn add jest-openapi","lang":"bash","label":"yarn"},{"cmd":"pnpm add jest-openapi","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides the core OpenAPI validation logic used by jest-openapi.","package":"openapi-response-validator","optional":false},{"reason":"Required for TypeScript compilation, specifically for handling HTTP response types internally, as of v0.14.2.","package":"@types/request","optional":true},{"reason":"Required for TypeScript compilation, specifically for handling HTTP response types internally, as of v0.14.2.","package":"@types/superagent","optional":true},{"reason":"This is a Jest plugin and requires Jest as a testing framework.","package":"jest","optional":true}],"imports":[{"note":"The package exports a default function. CommonJS users must access it via `.default`.","wrong":"const jestOpenAPI = require('jest-openapi');","symbol":"jestOpenAPI","correct":"import jestOpenAPI from 'jest-openapi';"},{"note":"This is the correct CommonJS `require` pattern. Attempting to import named exports will fail as it only provides a default export.","wrong":"import { jestOpenAPI } from 'jest-openapi';","symbol":"jestOpenAPI","correct":"const jestOpenAPI = require('jest-openapi').default;"},{"note":"This is a Jest matcher extended by jest-openapi, and is automatically available after calling `jestOpenAPI('path/to/spec.yml')`.","symbol":"toSatisfyApiSpec","correct":"expect(response).toSatisfyApiSpec();"}],"quickstart":{"code":"import axios from 'axios';\nimport jestOpenAPI from 'jest-openapi';\nimport path from 'path';\n\n// Point to your OpenAPI spec file. Ensure the path is correct.\nconst openApiSpecPath = path.resolve(__dirname, './openapi.yml');\n\n// Load your OpenAPI spec into the plugin once per test suite.\n// This makes the custom matchers available globally within Jest's context.\njestOpenAPI(openApiSpecPath);\n\ndescribe('API Endpoint Validation', () => {\n  it('should validate GET /users against OpenAPI spec', async () => {\n    // Simulate an HTTP response from your server\n    // Replace with your actual API call (e.g., using axios, supertest)\n    const res = await axios.get('http://localhost:3000/users');\n\n    expect(res.status).toEqual(200);\n\n    // Assert that the HTTP response satisfies the OpenAPI spec\n    expect(res).toSatisfyApiSpec();\n  });\n\n  it('should validate a specific object against a schema', () => {\n    const userObject = { id: 1, name: 'John Doe', email: 'john.doe@example.com' };\n    // Assuming 'User' is a defined schema in your openapi.yml\n    expect(userObject).toSatisfySchemaInApiSpec('User');\n  });\n});","lang":"typescript","description":"Demonstrates initializing jest-openapi with an OpenAPI spec and using `toSatisfyApiSpec()` to validate an HTTP response and `toSatisfySchemaInApiSpec()` for an object."},"warnings":[{"fix":"Review your tests that assert on specific error messages or subtle validation edge cases, as they might need adjustments. Ensure your API still passes validation against the updated dependency.","message":"The underlying validation dependency `openapi-response-validator` was updated from v3 to v9 in v0.14.0. This might introduce changes in validation rules, behavior, and specifically, the error messages returned for validation failures.","severity":"breaking","affected_versions":">=0.14.0"},{"fix":"Change `const jestOpenAPI = require('jest-openapi');` to `const jestOpenAPI = require('jest-openapi').default;`.","message":"When using CommonJS `require`, the `jest-openapi` module exports a default function, which must be accessed via `.default`. Directly requiring without `.default` will result in an undefined module.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure `jestOpenAPI('path/to/your/spec.yml')` is executed once in your test setup (e.g., `setupFilesAfterEnv` in Jest config or at the top of a test file) before any tests run that use its matchers. Verify the path is correct and the file exists.","message":"The `jestOpenAPI()` function must be called with a valid path to your OpenAPI specification file (YAML or JSON) or an OpenAPI object before `toSatisfyApiSpec()` or `toSatisfySchemaInApiSpec()` can be used. Failure to do so will result in Jest matcher errors.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure `jestOpenAPI('path/to/spec.yml');` is called once in your test setup or at the beginning of the test file where the matchers are used. Also, check that the `import jestOpenAPI from 'jest-openapi';` or `const jestOpenAPI = require('jest-openapi').default;` statement is present.","cause":"The jest-openapi matchers have not been loaded or initialized correctly into Jest's environment.","error":"TypeError: expect(...).toSatisfyApiSpec is not a function"},{"fix":"Inspect the detailed error message provided by jest-openapi. It will pinpoint which part of the response (e.g., status code, header, body property) violated the spec. You will then need to either adjust your API implementation to match the spec or update your OpenAPI specification to accurately reflect the API's current behavior.","cause":"The actual HTTP response object (status, headers, body) or the validated object does not conform to the schema defined in your OpenAPI specification for the given request path and method.","error":"ValidationError: Response does not match OpenAPI spec: ..."},{"fix":"Double-check the provided path string. Ensure it is absolute or correctly relative to the current working directory or the test file. Verify that the file exists, is readable, and contains valid YAML or JSON conforming to the OpenAPI specification. If providing an object, ensure it is a correctly structured OpenAPI definition.","cause":"The argument provided to `jestOpenAPI()` is either an incorrect file path, a non-existent file, or an invalid OpenAPI object.","error":"Error: 'path/to/openapi.yml' is not a valid file path or object."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}