cypress-schema-validator
v2.0.0
Published
Lightweight Cypress plugin for API schema validation. It leverages both the AJV validator (for plain JSON schemas, Swagger documents, and OpenAPI schemas) and the Zod validator (for Zod schemas).
Downloads
3,919
Maintainers
Readme
cypress-schema-validator
A Cypress plugin for API schema validation. It leverages the core-ajv-schema-validator powered by the AJV package (for plain JSON schemas, Swagger documents, and OpenAPI schemas) as well as the core-zod-schema-validator powered by the ZOD package (for Zod schemas).

MAIN FEATURES
✔️ Cypress command cy.validateSchema() (and alias cy.validateSchemaAjv()) performs a JSON Schema Validation and reports errors in the responses of network requests made with cy.request().
- Schemas are provided as JSON objects, which can come from a Cypress fixture.
- Supports Plain JSON schemas, OpenAPI 3.x schema documents and Swagger 2.0 schema documents.
- Utilizes the core-ajv-schema-validator, leveraging the Ajv JSON Schema Validator .
✔️ Cypress command cy.validateSchemaZod() identifies and reports Zod schema validation errors in the responses of network requests made with cy.request().
- Schemas are provided as Zod objects, which can come from a Cypress fixture.
- Uses the core-zod-schema-validator , leveraging the Zod Schema Validator.
✔️ The commands are chainable with cy.request() and yield the original API response.
✔️ Provides a summary of schema errors as well as a list of individual validation errors directly in the Cypress log.
✔️ By clicking on the schema errors summary in the Cypress log, the DevTools console outputs:
- Total number of schema errors.
- Full list of schema errors as provided by Ajv or Zod depending on the selected command.
- A nested tree view of the validated data, clearly indicating the errors and where they occurred in an easy-to-understand format.
✔️ Presents results to the user in a consistent format, regardless of whether the AJV Schema Validator or ZOD Validator is used.
✔️ Output the schema errors in the terminal when executing in run mode.
✔️ Allow custom styles (icons and text colors) to match the user's preferences for distinguishing schema errors.
✔️ Environment variable disableSchemaValidation to disable schema validation in your tests.
✔️ Environment variable generateReport to generate a report of the schema validation (JSON). - New in v2.0.0
✔️ Fully integrates with Gleb Bahmutov's @bahmutov/cy-api plugin, allowing JSON schema validations to be performed immediately after the cy.api() command.
- With the environment variable
enableMismatchesOnUIenabled, schema errors are displayed directly in the user interface of these plugins for enhanced visibility.
⭐⭐⭐ Example usage with @bahmutov/cy-api plugin
cy.api('/users/1').validateSchema(schema);For detailed examples of
cypress-schema-validatorused with the@bahmutov/cy-apiplugin in the Swagger Petstore API, refer to the sample test files: test-multiple-api-with-cy-api-override-style.js and test-multiple-api-with-cy-api.js.
⚠️⚠️⚠️ Deprecation Notice: cypress-plugin-api Removed in
cypress-schema-validatorv2.0.0 due to Cypress v16 compatibility issues (cy.env()andCypress.exposed()). Support is limited tocypress-schema-validatorv1.0.1 and below.
✔️✔️✔️ IMPORTANT NOTE: The
cypress-schema-validatorplugin replaces the legacycypress-ajv-schema-validator. It maintains full backward compatibility while extending the API to support Zod Schema Validation in addition to AJV Schema Validation.
TABLE OF CONTENTS
- cypress-schema-validator
- MAIN FEATURES
- COMPATIBILITY
- INSTALLATION
- CONFIGURATION
- ABOUT JSON SCHEMAS AND SCHEMA VALIDATORS
- API REFERENCE
- USAGE EXAMPLES
- SCHEMA VALIDATION RESULTS
- DISABLE JSON SCHEMA VALIDATION IN YOUR TESTS
- LICENSE
- CONTRIBUTING
- CHANGELOG
- EXTERNAL REFERENCES
COMPATIBILITY
Cypress v15.10+
- Use cypress-schema-validator v2.0.0 or greater
- Use of
cy.envandCypress.expose(https://docs.cypress.io/app/references/migration-guide#Migrating-away-from-Cypressenv) - Support integration with the latest version of
@bahmutov/cy-api - Decommissioned integration with
cypress-plugin-api, which has not been updated to support Cypress v16.
Cypress v12.0.0 - v15.9.0
- Ajv 8.16.0 or higher
- ajv-formats 3.0.1 or higher
- Support integration with
@bahmutov/cy-apiandcypress-plugin-apiplugins
For Typescript projects also:
- TypeScript 4.5+
- You must enable strict mode in your
tsconfig.json. This is a best practice for all TypeScript projects.
INSTALLATION
npm install -D cypress-schema-validatorCONFIGURATION
Configure the report directory using the
reportsFolderparameter incypress.config.js. Defaults tocypress/reports.module.exports = defineConfig({ // New config option for cypress-schema-validator v2.0.0 reportsFolder: 'cypress/reports', // Rest of your configuration // [...] })Add the following lines either to your
cypress/support/commands.jsto include the custom command and function globally, or directly in the test file that will host the schema validation tests:import 'cypress-schema-validator';To disable schema validation even when the
cy.validateSchema()command is present in the test, set the Cypress environment variable or exposed variabledisableSchemaValidationtotrue. By default, schema validation is enabled.To enable the display of schema errors directly in the user interfaces of the
@bahmutov/cy-apiandcypress-plugin-apiplugins, set the Cypress environment variable or exposed variableenableMismatchesOnUItotrue. By default, this feature is disabled.To enable the generation of JSON schema validation reports, set the generateReport environment or exposed variable to json (disabled by default). Only json is supported at this time.
✳️Starting in Cypress v15.10.0, you can configure cypress-schema-validator using the two environment variables
disableSchemaValidationandenableMismatchesOnUI. These can be defined either as regular (non-exposed) or exposed Cypress environment variables. This ensures full backward compatibility with previous versions and existing projects, configurations, and tests created using versions of cypress-schema-validator prior to Cypress v15.10.0.**.NOTE: If an environment variable is defined both as exposed and non-exposed, the non-exposed value takes priority.
ABOUT JSON SCHEMAS AND SCHEMA VALIDATORS
JSON Schema
JSON Schema is a hierarchical, declarative language that describes and validates JSON data.
OpenAPI 3.x and Swagger 2.0 Schema Documents
The OpenAPI Specification (formerly Swagger Specification) are schema documents to describe your entire API (in JSON format or XML format). So a schema document will contain multiple schemas, one for each supported combination of Endpoint - Method - Expected Response Status (also called path) by that API.
Ajv JSON Schema Validator
AJV, or Another JSON Schema Validator, is a JavaScript library that validates data objects against a JSON Schema structure.
It was chosen as the core engine of the core-ajv-schema-validator plugin because of its versatility, speed, capabilities, continuous maintenance, and excellent documentation. For more information on Ajv, visit the Ajv official website.
Ajv supports validation of the following schema formats: JSON Schema, OpenAPI 3.x specification, and Swagger 2.0 specification. However, Ajv needs to be provided with the specific schema to be validated for an endpoint, method, and expected response; it cannot process a full OpenAPI 3.x or Swagger 2.0 schema document by itself.
The cypress-schema-validator plugin simplifies this by obtaining the correct schema definition for the endpoint you want to test. You just need to provide the full schema document (OpenAPI or Swagger) and the path to the schema definition of the service you want to validate for your API (Endpoint - Method - Expected Response Status).
Note: The Ajv instance used in this plugin (
cypress-schema-validator) is configured with the options{ allErrors: true, strict: false }to display all validation errors and disable strict mode.
Zod Schema Validator
Zod is a TypeScript-first schema declaration and validation library that allows defining schemas directly in TypeScript while providing robust type detection within your code.
It was chosen as the core engine of the core-zod-schema-validator plugin due to its developer-friendly nature, versatility, and seamless integration into modern TypeScript workflows. Its intuitive API, extensive validation capabilities, and active maintenance make it a powerful tool for schema validation. For more information on Zod, visit the Zod official website.
The cypress-schema-validator plugin integrates Zod by enabling developers to supply Zod schemas directly for validation. You define the schema for the service and endpoint you want to validate, and the plugin ensures that the API responses adhere to the specified structure.
API REFERENCE
cy.validateSchema(schema[, path[, issuesStyles]]) (and alias cy.validateSchemaAjv(schema[, path[, issuesStyles]]))
It validates the JSON data in the response body against the provided Plain JSON schema, OpenAPI and Swagger document format using the AJV Schema Validator.
It is expected to be chained to an API response (from a cy.request() or cy.api()).
Parameters
schema(object) The schema to validate against. Supported formats are plain JSON schema, Swagger, and OpenAPI documents.path(object, optional) This second parameter represents the path to the schema definition in a Swagger or OpenAPI document and is determined by three properties:endpoint(string, optional): The endpoint path.method(string, optional): The HTTP method. Defaults to 'GET'.status(integer, optional): The response status code. If not provided, defaults to 200.
issuesStyles(object, optional) An object with the icons and HEX colors used to flag the issues. If not provided, it will use the default icons defined in the plugin. Includes the following properties:iconPropertyError(string, optional): The icon used to flag type errors in the data. Support emojis.iconPropertyMissing(string, optional): The icon used to flag type errors in the data. Support emojis.colorPropertyError(string, optional): The HEX color used to flag the property error.colorPropertyMissing(string, optional): The HEX color used to flag the missing property.
Returns
Cypress.Chainable: The response object wrapped in aCypress.Chainable.
Throws
Error: If any of the required parameters are missing or if the schema or schema definition is not found.
Example providing a Plain JSON schema:
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchema(schema);or
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchemaAjv(schema);Example providing a Plain JSON schema and custom issuesStyles:
const issuesStylesOverride = {
iconPropertyError: '🟦', colorPropertyError: '#5178eb',
iconPropertyMissing: '🟪', colorPropertyMissing: '#800080'
}
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchema(schema, undefined, issuesStylesOverride);or
const issuesStylesOverride = {
iconPropertyError: '🟦', colorPropertyError: '#5178eb',
iconPropertyMissing: '🟪', colorPropertyMissing: '#800080'
}
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchemaAjv(schema, undefined, issuesStylesOverride);Example providing an OpenAPI 3.0.1 or Swagger 2.0 schema documents and path to the schema definition:
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchema(schema, { endpoint: '/users/{id}', method: 'GET', status: 200 });or
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchemaAjv(schema, { endpoint: '/users/{id}', method: 'GET', status: 200 });Example providing an OpenAPI 3.0.1 or Swagger 2.0 schema documents, path to the schema definition and custom issuesStyles:
const issuesStylesOverride = {
iconPropertyError: '🟦', colorPropertyError: '#5178eb',
iconPropertyMissing: '🟪', colorPropertyMissing: '#800080'
}
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchema(schema, { endpoint: '/users/{id}', method: 'GET', status: 200 }, issuesStylesOverride);or
const issuesStylesOverride = {
iconPropertyError: '🟦', colorPropertyError: '#5178eb',
iconPropertyMissing: '🟪', colorPropertyMissing: '#800080'
}
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchemaAjv(schema, { endpoint: '/users/{id}', method: 'GET', status: 200 }, issuesStylesOverride);Path Parameter
Using the path defined by { endpoint, method, status }, the plugin will automatically take the schema $ref for that definition, find it in the components section, and use it in the schema validation.

cy.validateSchemaZod(schema[, issuesStyles])
It validates the JSON data in the response body against the provided Zod schema using the ZOD Schema Validator.
It is expected to be chained to an API response (from a cy.request() or cy.api()).
Parameters
schema(object) The schema to validate against. Supported format is Zod Schema.issuesStyles(object, optional) An object with the icons used to flag the schema issues. If not provided, it will use the default icons defined in the plugincore-zod-schema-validator. Includes the following properties:iconPropertyError(string, optional): The icon used to flag type errors in the data. Support emojis.iconPropertyMissing(string, optional): The icon used to flag type errors in the data. Support emojis.colorPropertyError(string, optional): The HEX color used to flag the property error.colorPropertyMissing(string, optional): The HEX color used to flag the missing property.
Returns
Cypress.Chainable: The response object wrapped in aCypress.Chainable.
Throws
Error: If any of the required parameters are missing or if the schema or schema definition is not found.
Example providing a Zod schema:
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchemaZod(schema);Example providing a Zod schema nd custom issuesStyles:
const issuesStylesOverride = {
iconPropertyError: '🟦', colorPropertyError: '#5178eb',
iconPropertyMissing: '🟪', colorPropertyMissing: '#800080'
}
cy.request('GET', 'https://awesome.api.com/users/1')
.validateSchemaZod(schema, issuesStylesOverride);
USAGE EXAMPLES
Examples For AJV Schema Validation USAGE-EXAMPLES-AJV.md.
Includes detailed examples for the use cases:
.validateSchema()command with a Plain JSON schema..validateSchema()command with a Plain JSON schema and overridingissuesStyles.validateSchema()command with an OpenAPI 3.0.1 schema document..validateSchemaAjv()command with a Swagger 2.0 schema document..validateSchema()command with a Swagger 2.0 schema document and overridingissuesStyles..validateSchemaAjv()command in conjunction withcy.api()from the@bahmutov/cy-apiorcypress-plugin-apiplugins.
Examples For ZOD Schema Validation USAGE-EXAMPLES-ZOD.md.
Includes detailed examples for the use cases:
.validateSchemaZod()command with a Zod Schema..validateSchemaZod()command with a Zod Schema and overridingissuesStyles..validateSchemaAZod()command withcy.api()from Plugin@bahmutov/cy-apiorcypress-plugin-apiplugins.
SCHEMA VALIDATION RESULTS
Results Outcome (Passed/Failed)
Here are some screenshots of schema validation tests run in Cypress for the different test results.
Test Passed ✔️
When a test passes, the Cypress log will show the message: "✔️ PASSED - THE RESPONSE BODY IS VALID AGAINST THE SCHEMA.".

Test Failed ❌
When a test fails, the Cypress log will show the message: "❌ FAILED - THE RESPONSE BODY IS NOT VALID AGAINST THE SCHEMA"; indicating the total number of errors: (Number of schema errors: N).
Also, the Cypress log will show an entry for each of the individual schema validation errors as provided by AJV or ZOD. The errors that correspond to missing fields in the data validated are marked with the symbol ❌, and the rest of the errors like with the symbol ⚠️.

Detailed Error View in the Console
If you open the Console in the browser DevTools, and click on the summary line for the schema validation error in the Cypress log, the console will display detailed information about all the errors. This includes:
- Message containing the schema analysis results.
- The total number of errors.
- Complete list of errors provided by the core Schema Validator (AJV or ZOD).
- A user-friendly view of the mismatches between the validated data and the JSON schema, highlighting where each validation error occurred and the exact reason for the mismatch.

Test Failed with More than 10 Errors ➕
When there are more than 10 schema validation errors, the Cypress log will show only the first 10 and, at the end of the list, an additional line indicating "...and N more errors.".
If you click on the "...and N more errors." line in the Cypress log, the browser console will show additional details for the errors grouped under that entry as provided by the core Schema Validator (AJV or ZOD).

Schema errors in the Terminal when executing in run mode
In case the tests are executed in run mode and there are schema errors, these will be displayed in the Terminal as provided by the AJV or ZOD validators.

Integration with other Cypress API Plugins
Integration with Gleb Bahmutov's @bahmutov/cy-api Plugin
When the Cypress environment variable enableMismatchesOnUI is set to true, and you have imported the @bahmutov/cy-api plugin into your cypress/support/commands.js or test file, schema validation mismatches will be displayed directly in the plugin's UI in a user-friendly format.


Custom Styles for Validation Errors
The Custom Styles for Validation Errors feature allows users to personalize the display of schema validation issues for enhanced clarity. By specifying custom styles through the issuesStyles object, users can customize icons and HEX color codes to flag specific validation errors visually.
These customizable styles ensure flexibility and improved error identification suited to individual preferences.

Results for AJV Schema Validation vs ZOD Schema Validation
One of the significant advantages of using this plugin is that it presents results to the user in a consistent format, regardless of whether the AJV Schema Validator or ZOD Validator is used. This ensures that if the plugin's user decides to switch between validators, the results remain uniform and consistent.
This provides a layer of abstraction that manages how the results are presented, allowing the user to focus solely on the results themselves.
If we compare the results presented by the cypress-schema-plugin for AJV validation and ZOD validation side by side, we can observe that the data mismatch results displayed in the Cypress UI, as well as the nested tree view of the validated data, remain consistent. This ensures an identical user experience when identifying schema issues.
The only slight differences are the schema error properties presented in the Cypress Log and the console, as these are provided by the specific validator. This allows users to inspect the results in the original validator format, if they are more familiar with it.

ENABLE CREATION OF JSON REPORTS FOR SCHEMA VALIDATIONS
You can enable the generation of JSON reports for your schema validations by setting the Cypress environment (or exposed) variable generateReport to json.
Note: This feature is disabled by default, and json is currently the only supported format.
When enabled, each validation command cy.validateSchema(), cy.validateSchemaAjv(), or cy.validateSchemaZod() generates a report file in the directory configured by reportsFolder in cypress.config.js.
File Name Format
schema-validation-report-{uniqueId}_{timestamp}.json
Where:
uniqueIdis generated with Cypress utilityCypress._.uniqueId('id')(for example:id1,id2,id36).timestampis generated from ISO date-time and normalized for file systems by replacing:and.with-.
Example:
schema-validation-report-id36_2026-06-06T23-58-42-001Z.json
JSON Report File Content
Each generated report is a JSON object with the following structure:
Example:
{
"timestamp": "2026-06-07T00-45-49-966Z",
"test": "ALL TESTS SHOULD FAIL > Schema Validation for Swagger 2.0 > POST /service1 (401 Response)",
"validationResults": {
"errors": [
{
"instancePath": "/code",
"schemaPath": "#/definitions/ErrorResponse/properties/code/type",
"keyword": "type",
"params": {
"type": "integer"
},
"message": "must be integer"
},
{
"instancePath": "/message",
"schemaPath": "#/definitions/ErrorResponse/properties/message/type",
"keyword": "type",
"params": {
"type": "string"
},
"message": "must be string"
}
],
"dataMismatches": {
"code": "⚠️ null must be integer",
"message": "⚠️ 123456 must be string"
}
},
"data": {
"code": null,
"message": 123456
}
}Top-level properties
timestamp(string): Report creation date-time in ISO-like format used in the file name (for example:2026-06-06T23-58-42-001Z).test(string): Full Cypress test path/title where the validation was executed.validationResults(object): Validation output (errors and highlighted mismatches).data(array | object): Original response payload that was validated.
validationResults properties
errors(array): List of validation errors returned by the active validator (Ajv or Zod).dataMismatches(array | object): Copy of validateddataresponse with mismatch markers added by the plugin.dataMismatchesmirrors thedatastructure and adds marker strings (icon + message) at failing paths.- Examples of a field mismatches:
"code": "⚠️ null must be integer""createdDate": "❌ Missing property 'createdDate'
- Note: Top-level property
dataalways stores the original validated payload unchanged (same shape as the API response).
DISABLE JSON SCHEMA VALIDATION IN YOUR TESTS
You can disable schema validation in your tests by setting the Cypress environment (or exposed) variable disableSchemaValidation to true.
When schema validation is disabled for a test, the Cypress log and the browser console will display the following message:

LICENSE
This project is licensed under the MIT License. See the LICENSE file for more details.
CONTRIBUTING
First off, thanks for taking the time to contribute!
To contribute, please follow the best practices promoted by GitHub on the Contributing to a project page.
And if you like the project but just don't have the time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
- Star the project
- Promote it on social media
- Refer this project in your project's readme
- Mention the project at local meetups and tell your friends/colleagues
- Buying me a coffee or contributing to a training session, so I can keep learning and sharing cool stuff with all of you.
Thank you for your support!
CHANGELOG
[2.0.0]
- Added support to generate a schema validation report (JSON).
- Added support for the new environment variable handling in v15.10+ (
cy.envandCypress.expose). - Migrated package to Cypress v15.16.0.
- Major release due a breaking change that will be introduced in the Cypress v16 release.
- Cypress.env deprecated in Cypress v15.10.0 and no loger supported in Cypress v16.0.0.
- cypress-ajv-schema-validator v2.0.0 is not supported on versions earlier than v15.10.0.
- Decommissioned support for
cypress-plugin-api, as it has not been updated to work withcy.env()andCypress.exposed().
[1.0.1]
- Update documentation regarding the legacy plugin
cypress-ajv-schema-validator.
[1.0.0]
- Initial release of
cypress-schema-validator, supporting both AJV and ZOD schema validations.
[cypress-ajv-schema-validator 2.0.1]
- Predecessor to the
cypress-schema-validator. - The legacy plugin
cypress-ajv-schema-validatorhas been decommissioned and is no longer officially supported.
