0

I am using Cypress.io framework, and I would like to implement chai plugin called chai-openapi-response-validator which contains a new assertion called satisfyApiSpec

https://github.com/openapi-library/OpenAPIValidators/tree/master/packages/chai-openapi-response-validator

I tried to install and add the plugin to the plugins/index.js file, but the assertion inside the cypress test is failing with an error: Invalid Chai property: satisfyApiSpec

Is there another way to add this plugin, so the cypress / chai will learn a new assertion?

Ken White
  • 123,280
  • 14
  • 225
  • 444
smgrvtsch
  • 3
  • 3

1 Answers1

0

You can add it at the top of the spec, or in cypress/support/index.js for all specs.

cypress/plugins is for node plugins, but browser-side plugins can be imported directly into specs or support/index.js.

const chai = require('chai');
const chaiResponseValidator = require('chai-openapi-response-validator').;
chai.use(chaiResponseValidator('path/to/openapi.yml'));

Getting around the fs.read() problem for this chai plugin

From npm: chai-openapi-response-validator

Loading your OpenAPI spec (3 different ways):

  1. From an object:
// Load that OpenAPI object into this plugin
chai.use(chaiResponseValidator(openApiSpec));

so you can require the object before initializing the plugin

const chai = require('chai');
const chaiResponseValidator = require('chai-openapi-response-validator');
const openApiSpec = require('path/to/openapi.yml');
chai.use(chaiResponseValidator(openApiSpec));

An alternative - take a look at cy-spok to validate the API response.

The linked video shows in action with an intercept.

Fody
  • 23,754
  • 3
  • 20
  • 37
  • Thanks, looks like it loaded, because I have a new error with fs.read > Object.setPrototypeOf: expected an object or null, got undefined node_modules/graceful-fs/polyfills.js:139:1 // This ensures `util.promisify` works as it does for native `fs.read`. if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) return read })(fs.read) – smgrvtsch Apr 14 '22 at 10:00
  • Ok, looks like I was wrong for this particular chai plugin. It uses `fs.read` which is only available in nodejs (not the browser). Need to check if there's a different way to call `chai.use(chaiResponseValidator)` by requiring `openapi.yml` and passing in the file contents. – Fody Apr 14 '22 at 11:48
  • Another note - take a look at [cy-spok](https://github.com/bahmutov/cy-spok) as an alternate way of validating the API response. – Fody Apr 15 '22 at 00:04