DEV Community

Alex Spinov
Alex Spinov

Posted on

Cypress Has a Free API You Should Know About

Cypress is famous for E2E testing, but its API goes far beyond simple test commands. Custom commands, plugins, network stubbing, and component testing make it a complete testing platform.

Custom Commands API

Extend Cypress with reusable commands:

// cypress/support/commands.js
Cypress.Commands.add("login", (email, password) => {
  cy.session([email, password], () => {
    cy.visit("/login")
    cy.get("[data-cy=email]").type(email)
    cy.get("[data-cy=password]").type(password)
    cy.get("[data-cy=submit]").click()
    cy.url().should("include", "/dashboard")
  })
})

Cypress.Commands.add("createUser", (user) => {
  return cy.request({
    method: "POST",
    url: "/api/users",
    body: user,
    headers: { Authorization: `Bearer ${Cypress.env("API_TOKEN")}` }
  })
})
Enter fullscreen mode Exit fullscreen mode
// In tests
cy.login("admin@test.com", "password123")
cy.createUser({ name: "John", role: "editor" })
Enter fullscreen mode Exit fullscreen mode

Network Stubbing with cy.intercept()

Control every network request:

// Stub API response
cy.intercept("GET", "/api/products", {
  statusCode: 200,
  body: [{ id: 1, name: "Widget", price: 9.99 }]
}).as("getProducts")

cy.visit("/products")
cy.wait("@getProducts")
cy.get(".product-card").should("have.length", 1)

// Modify real response
cy.intercept("GET", "/api/user", (req) => {
  req.continue((res) => {
    res.body.plan = "premium" // Override plan
    res.send()
  })
})

// Simulate errors
cy.intercept("POST", "/api/checkout", {
  statusCode: 500,
  body: { error: "Payment failed" }
})
Enter fullscreen mode Exit fullscreen mode

Task API — Run Node.js Code

Execute server-side operations during tests:

// cypress.config.js
module.exports = {
  e2e: {
    setupNodeEvents(on) {
      on("task", {
        seedDatabase(data) {
          return db.seed(data)
        },
        queryDatabase(sql) {
          return db.raw(sql).then(r => r.rows)
        },
        clearEmails() {
          return mailServer.clear()
        },
        getLastEmail(to) {
          return mailServer.getLastEmail(to)
        }
      })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
// In test
cy.task("seedDatabase", { users: 10, posts: 50 })
cy.task("clearEmails")

// Test email flow
cy.get("#reset-password").click()
cy.task("getLastEmail", "user@test.com").then((email) => {
  const resetLink = extractLink(email.html)
  cy.visit(resetLink)
})
Enter fullscreen mode Exit fullscreen mode

Component Testing

Test React/Vue/Angular components in isolation:

import { mount } from "cypress/react18"
import ProductCard from "./ProductCard"

describe("ProductCard", () => {
  it("displays product info", () => {
    const product = { name: "Widget", price: 29.99, inStock: true }
    mount(<ProductCard product={product} />)

    cy.contains("Widget").should("be.visible")
    cy.contains("$29.99").should("be.visible")
    cy.get(".add-to-cart").should("be.enabled")
  })

  it("disables button when out of stock", () => {
    const product = { name: "Widget", price: 29.99, inStock: false }
    mount(<ProductCard product={product} />)
    cy.get(".add-to-cart").should("be.disabled")
  })
})
Enter fullscreen mode Exit fullscreen mode

Cypress Cloud API

Access test results programmatically:

curl -H "Authorization: Bearer $CYPRESS_RECORD_KEY" \
  "https://cloud.cypress.io/api/v1/projects/$PROJECT_ID/runs?limit=5"
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Custom commands create reusable test utilities
  • cy.intercept() stubs, modifies, or monitors network requests
  • Task API runs Node.js code from tests
  • Component testing tests UI components in isolation
  • cy.session() caches authentication across tests
  • Cypress Cloud provides analytics and parallelization

Explore Cypress docs for the full API.


Building web scrapers or data pipelines? Check out my Apify actors for ready-made solutions, or email spinov001@gmail.com for custom development.

Top comments (0)