Cypress API Testing Plugin
Cypress Plugin API is a tool for enhancing API testing within the Cypress test runner by providing a user interface similar to Postman. It extends the standard `cy.request()` command with `cy.api()`, which visually logs details about API calls, including URLs, headers, request/response bodies, and cookies, directly into the Cypress App UI. These details are viewable through time-travel snapshots. Key features include JSON data object/array folding, HTTP method color coding, response size calculation, and options for sensitive data masking (like credentials) and integrating API calls seamlessly into UI test flows using `snapshotOnly` mode. The plugin currently maintains version `2.11.2`, released on July 14, 2024, with a consistent cadence of bug fixes and minor feature additions. It ships with TypeScript types to provide a better development experience.
Common errors
-
TypeError: cy.api is not a function
cause The `cypress-plugin-api` plugin has not been correctly imported into your Cypress support file.fixAdd `import 'cypress-plugin-api'` to your `cypress/support/e2e.ts` (or `.js`) file. -
Error: Webpack compilation failed: Cannot find module 'cypress-plugin-api'
cause The `cypress-plugin-api` package is either not installed or webpack cannot resolve its path.fixEnsure the package is installed via `npm install cypress-plugin-api` or `yarn add cypress-plugin-api`. Check your `cypress/support/e2e.{js,ts}` path and `tsconfig.json` if applicable. -
Property 'api' does not exist on type 'Chainable<any>'
cause TypeScript is not correctly picking up the type augmentations provided by `cypress-plugin-api` for the `cy` object.fixVerify that `cypress-plugin-api` is listed in the `types` array of your `tsconfig.json` (e.g., `"types": ["cypress", "cypress-plugin-api"]`) or that `/// <reference types="cypress-plugin-api" />` is in a relevant `.d.ts` file or `cypress/support/e2e.ts`.
Warnings
- breaking This plugin requires Cypress version 10 or newer. Installing with older Cypress versions will result in command `cy.api()` not being available or unexpected behavior.
- gotcha The `cy.api()` command is added globally by importing the plugin in `cypress/support/e2e.{js,ts}`. Failing to import it will result in `cy.api is not a function` errors.
- gotcha The `requestMode` option, which applies `cy.api()`'s UI features to `cy.request()`, is `false` by default. If you intend for all `cy.request()` calls to display in the plugin's UI, you must explicitly enable this option in your Cypress configuration.
- gotcha When using both `hideCredentials: true` and `hideCredentialsOptions`, the `hideCredentialsOptions` will override the default sensitive fields hidden by `hideCredentials`. Ensure all desired fields are explicitly listed in `hideCredentialsOptions` if you are using it.
- gotcha Incorrect type imports or `tsconfig.json` configuration can lead to TypeScript errors for `cy.api()` or `Cypress.env()` properties, despite the plugin shipping with types. Recent releases have specifically addressed type-related bugs.
Install
-
npm install cypress-plugin-api -
yarn add cypress-plugin-api -
pnpm add cypress-plugin-api
Imports
- *
import { api } from 'cypress-plugin-api'import 'cypress-plugin-api'
- *
const api = require('cypress-plugin-api')require('cypress-plugin-api') - Cypress global types
/// <reference types="cypress-plugin-api" />
Quickstart
import { defineConfig } from 'cypress'
// cypress.config.ts
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
// Optional: Add an event listener to log something during setup
on('task', {
log(message) {
console.log(message)
return null
},
})
return config
},
baseUrl: 'http://localhost:3000', // Ensure your API is running here
env: {
snapshotOnly: false, // Default: shows full UI for API calls
hideCredentials: true,
myAuthToken: 'secret-token-123',
apiUser: 'testuser',
apiPass: 'testpassword',
}
},
})
// cypress/support/e2e.ts
import 'cypress-plugin-api'
// You can also add other Cypress commands or configurations here
// cypress/e2e/api.cy.ts
describe('Cypress Plugin API features', () => {
beforeEach(() => {
// Assuming your app serves simple endpoints for demonstration
// For a real app, ensure your dev server is running before tests
})
it('should make a GET API call and display full UI details', () => {
cy.api('/data').then((response) => {
expect(response.status).to.eq(200)
expect(response.body).to.have.property('message', 'Hello from API')
})
})
it('should make a POST API call with hidden credentials and custom options', {
env: {
hideCredentials: true,
hideCredentialsOptions: {
headers: ['authorization'],
body: ['password'],
query: ['apiKey']
}
}
}, () => {
cy.api({
method: 'POST',
url: '/login',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Cypress.env('myAuthToken')}` // This header will be hidden
},
body: {
username: Cypress.env('apiUser'),
password: Cypress.env('apiPass') // This body field will be hidden
},
qs: {
apiKey: 'super-secret-key' // This query param will be hidden
}
}).then((response) => {
expect(response.status).to.eq(200)
expect(response.body).to.have.property('success', true)
})
})
it('should combine UI and API testing with snapshotOnly mode', { env: { snapshotOnly: true } }, () => {
cy.visit('/') // Navigate to your web application
cy.get('h1').should('contain', 'Welcome') // Interact with UI
cy.api('/users').then((response) => {
expect(response.status).to.eq(200)
expect(response.body).to.be.an('array')
})
cy.get('#user-list').should('exist') // More UI interaction after API call
})
})