Coder Social home page Coder Social logo

Comments (3)

jc21 avatar jc21 commented on July 17, 2024

hmm here's an example of a project I have that uses Cypress v12.13.0:

cypress/config/ci.js

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  requestTimeout:        30000,
  defaultCommandTimeout: 20000,
  e2e: {
    setupNodeEvents(on, config) {
      return require("../plugins/index.js")(on, config);
    },
    env: {
      verbose:     true,
      swaggerFile: "{{baseUrl}}/schema.json"
    }
  }
});

cypress/plugins/index.js

const { SwaggerValidation } = require("@jc21/cypress-swagger-validation");

module.exports = (on, config) => {
  // Replace swaggerFile config var wildcard
  if (typeof config.env.swaggerBase !== "undefined") {
    config.env.swaggerFile = config.env.swaggerFile.replace("{{baseUrl}}", config.baseUrl);
  }

  // Plugin Events
  on("task", SwaggerValidation(config));
  // ...
  return config;
};

cypress/support/commands.js

// ...
/**
 * Check the swagger schema:
 *
 * @param {string}  method        API Method in swagger doc, "get", "put", "post", "delete"
 * @param {number}  statusCode    Status Code for response item in swagger doc
 * @param {string}  path          Swagger doc endpoint path, exactly as defined in swagger doc
 * @param {*}       data          The API response data to check against the swagger schema
 */
Cypress.Commands.add("validateSwaggerSchema", (method, statusCode, path, data) => {
  cy.task("validateSwaggerSchema", {
    file:           Cypress.env("swaggerFile"),
    endpoint:       path,
    method:         method,
    statusCode:     statusCode,
    responseSchema: data,
    verbose:        !!Cypress.env("verbose"),
  }).should("equal", null);
});
// ...

Then using your example test it would be:

describe('API Test', () => {
  it.only('should satisfy OpenAPI spec', () => {
    MyEndpoint.getAll().then((response) => {
      cy.validateSwaggerSchema("get", 200, "/v7/account-groups", response.body);
    });
  });
});

This approach allows you to reuse a helper command and cut down your individual test code.

The replacement of the {{baseUrl}} in the filename is handy if you want to run the tests against different environments, assuming that the schema file exists on the same domain as the API you're testing:

cypress run --config-file=cypress/config/ci.js --config "baseUrl=http://example.com"

from cypress-swagger-validation.

joaomper-TE avatar joaomper-TE commented on July 17, 2024

No luck there, I always get an empty object as a result of the validateSwaggerSchema task:
image

My files are pretty much the same as your example:

cypress/support/e2e.ts

import { myOtherCustomTask } from './commands/myOtherCustomTask';
import {validateSwaggerSchema} from "./commands/validateSwaggerSchema";

Cypress.Commands.addAll({
    myOtherCustomTask,
    validateSwaggerSchema
});

cypress/support/commands/validateSwaggerSchema.ts


import 'cypress-plugin-api';
import {ErrorObject} from "ajv";

const { _ } = Cypress;

declare global {
    // eslint-disable-next-line @typescript-eslint/no-namespace
    namespace Cypress {
        interface Chainable {
            validateSwaggerSchema(oasFile:string ,method, statusCode, path,data): Chainable<Promise<ErrorObject[] | null | Error | undefined>> //tried multiple things here, doesn't seem to be the issue
        }
    }
}

export function validateSwaggerSchema(oasFile, method, statusCode, path, data){
    cy.task("validateSwaggerSchema", {
        file:           oasFile,
        endpoint:       path,
        method:         method,
        statusCode:     statusCode,
        responseSchema: data,
        verbose:        true,
    }).should("equal", null);
}

cypress/plugins/index.ts

const { SwaggerValidation } = require("@jc21/cypress-swagger-validation");

module.exports = (on, config) => {
    // Replace swaggerFile config var wildcard
    if (typeof config.env.swaggerBase !== "undefined") {
        config.env.swaggerFile = config.env.swaggerFile.replace("{{baseUrl}}", config.baseUrl);
    }

    // Plugin Events
    on("task", SwaggerValidation(config));
    // ...
    return config;
};

And the test:

import {MyEndpoint} from "../../support/api/MyEndpoint-api";

describe('API Test', () => {
    it.only('should satisfy OpenAPI spec', () => {
        MyEndpoint.getAll().then((response) => {
            cy.validateSwaggerSchema('oas-with-wrong-things.json',
                "GET",
                200,
                "/v7/account-groups",
                response.body);
        });
    });
});

from cypress-swagger-validation.

joaomper-TE avatar joaomper-TE commented on July 17, 2024

Was able to find the issue using logs within cypress-swagger-validation/src/index.ts.
Our schemas have content application/hal+json and not application/json as in https://github.com/jc21/cypress-swagger-validation/blob/c97fe68e836ce5f467f753c8a039422f13e0d5d3/src/index.ts#L55C6-L55C6

Changing this correctly started validating the OAS.

from cypress-swagger-validation.

Related Issues (2)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.