← Back to list

Schema Validation in Cypress Using AJV

In this blog, we will explore how to perform Schema Validation using Cypress and AJV. Schema validation ensures that the data returned by…

HariPrasath · 2024-11-16 21:32 · 4 claps · 3.6 min read
#cypress-testing #api-testing #test-automation #json-schema-validator #ajv
Open on Medium ↗
Wiki topics: 📰 · Journalism & News

Schema Validation in Cypress Using AJV

In this blog, we will explore how to perform Schema Validation using Cypress and AJV. Schema validation ensures that the data returned by an API matches the expected structure, improving the quality and reliability of your tests.

Table of Contents

  1. Introduction to Schema Validation
  2. Setting Up the Project
  3. Writing the Schema Validation Command
  4. Creating the Test Case
  5. Loading and Using a JSON Schema
  6. Running the Test and Validating API Responses
  7. Conclusion

1. Introduction to Schema Validation

Schema validation is the process of ensuring that the data returned by an API complies with a predefined structure. This is critical in testing as it guarantees that the API responds with the correct data types, required fields, and valid values.

We will use Cypress, a powerful JavaScript end-to-end testing framework, and AJV (Another JSON Schema Validator), a fast JSON schema validator, to achieve this. The combination of these tools allows us to test API responses thoroughly, ensuring they meet the expected format.

2. Setting Up the Project

Before diving into the code, let’s first set up our Cypress project with AJV and necessary dependencies. Follow these steps to get started:

Install Cypress:

npm install cypress

Install AJV:

npm install ajv ajv-formats

Create the Folder Structure: Create the following folder structure to organize your files:

cypress/   
           ├── e2e/ 
                    └── schemaValidation.spec.cy.js   
           ├── fixtures/ 
                        └── example.json   
           └── support/ 
                        └── commands.js

3. Writing the Schema Validation Command

To start, we will write a custom Cypress command that uses AJV for schema validation. The command will check if the API response adheres to the specified schema.

commands.js

import Ajv from 'ajv';
import addFormats from 'ajv-formats';

// Add a custom Cypress command for schema validation
Cypress.Commands.add('schemaValidation', (schema, data) => {
  // Initialize AJV with strict mode enabled
  const ajv = new Ajv({ strict: true });
  addFormats(ajv); // Add format support (e.g., date-time, email)

  // Compile the schema
  const validate = ajv.compile(schema);

  // Perform validation
  const valid = validate(data);

  if (!valid) {
    // Log validation errors in a readable format
    cy.log('Schema validation failed. Errors:', JSON.stringify(validate.errors, null, 2));
    console.error('Schema validation errors:', validate.errors);

    // Throw an error with the validation issues
    throw new Error(`Schema validation failed: ${JSON.stringify(validate.errors, null, 2)}`);
  }

  // Assert that the validation passed
  expect(valid).to.be.true;
});

This code defines a custom Cypress command, schemaValidation, which takes two arguments:

  • schema: The JSON schema to validate against.
  • data: The actual response data from the API.

The Ajv instance is created with strict mode enabled to ensure data integrity, and we add additional formats such as date-time and email.

4. Creating the Test Case

Now that we have the schema validation logic, let’s create a test case where we fetch data from a sample API and validate it using the schema.

schemaValidation.spec.cy.js

describe('API Schema validation using AJV', () => {
  before(() => {
    // Fetch the response and alias it
    cy.request('GET', 'https://jsonplaceholder.typicode.com/posts').then((response) => {
      expect(response.status).to.equal(200); // Validate the response status
      cy.wrap(response.body).as('responseBody'); // Alias the response body
    });
  });

  it('Schema Validation', function () {
    // Load schema from the fixture
    cy.fixture('example.json').then((exampleSchema) => {
      const schemaPosts = exampleSchema.paths["/posts"].get.responses["200"].content["application/json"].schema;

      // Perform schema validation
      cy.get('@responseBody').then((responseBody) => {
        cy.schemaValidation(schemaPosts, responseBody);
      });
    });
  });
});

In this test case:

  • We make a GET request to https://jsonplaceholder.typicode.com/posts to retrieve the data.
  • We load the JSON schema from the fixtures folder and validate the API response against it using the schemaValidation custom command.

5. Loading and Using a JSON Schema

The schema we are using for this validation is defined in a file named example.json. This JSON schema defines the expected structure of the API response. Let's look at the contents of the schema:

example.json

{
  "openapi": "3.0.0",
  "info": {
    "title": "JSONPlaceholder API",
    "description": "Schema definition for the `/posts` endpoint",
    "version": "1.0.0"
  },
  "paths": {
    "/posts": {
      "get": {
        "summary": "Get list of posts",
        "description": "Returns a list of posts with user details.",
        "responses": {
          "200": {
            "description": "A successful response containing a list of posts",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "userId": {
                        "type": "integer"
                      },
                      "id": {
                        "type": "integer"
                      },
                      "title": {
                        "type": "string"
                      },
                      "body": {
                        "type": "string"
                      }
                    },
                    "required": ["userId", "id", "title", "body"]
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

This schema describes the structure of the data returned by the /posts endpoint. It expects an array of objects, each containing the fields userId, id, title, and body.

6. Running the Test and Validating API Responses

Once you have written the code, run your Cypress tests using the following command

npx cypress open

This will launch Cypress in interactive mode, where you can run the test and see the results. If the API response adheres to the schema, the test will pass. If there are discrepancies, Cypress will log the validation errors.

7. Conclusion

In this tutorial, we demonstrated how to integrate Cypress with AJV to perform schema validation on API responses. By validating the structure of your API responses, you can ensure that your APIs are behaving as expected and catch potential issues early in the development process.

Using AJV with Cypress not only improves the reliability of your tests but also allows for more flexible and powerful testing of REST APIs.

By following this approach, you can add robust schema validation to your Cypress tests and ensure that your API responses are consistent with your expectations.


메타데이터
post_id
4d08ae28fefa
slug
schema-validation-in-cypress-using-ajv-4d08ae28fefa
url
https://medium.com/@Hariprasath_V_S/schema-validation-in-cypress-using-ajv-4d08ae28fefa
canonical_url
https://medium.com/@Hariprasath_V_S/schema-validation-in-cypress-using-ajv-4d08ae28fefa
author_url
https://medium.com/@Hariprasath_V_S
status
ok
fetched_at
2026-07-22 03:37:30