← Back to Cypress Mastery
Intermediate18 min read

Fixtures & Mocking

Load fixture data and intercept API calls to stub responses.

Fixtures

cy.fixture loads JSON, text, or binary files from cypress/fixtures. Use for static test data, mock API responses, and file upload paths.

Fixtures cache per spec—mutating loaded object affects subsequent uses; clone if modifying.

cy.fixture("users").then((users) => {
  cy.get('[data-cy="email"]').type(users.admin.email);
});

cy.fixture("products.json").as("products");

cy.intercept

Intercept matches method and URL pattern (string, glob, regex). Provide static fixture, dynamic reply function, or spy passthrough to real backend.

Alias intercepts for wait and assertion. Route order matters—more specific patterns first.

cy.intercept("GET", "/api/products", { fixture: "products.json" }).as("getProducts");

cy.intercept("POST", "/api/orders", (req) => {
  req.reply({ statusCode: 201, body: { id: "order-1" } });
}).as("createOrder");

Response Stubbing

Stub error responses (500, 404) to test UI error handling without breaking backend. Delay responses to test loading spinners with req.reply delay.

Passthrough mode hits real API—use in staging integration tests sparingly in default suite.

  • Match URL patterns precisely to avoid stubbing wrong requests
  • Use middleware to modify req.body before passthrough
  • Log intercept hits in reply handler when debugging missing wait
cy.intercept("GET", "/api/products", {
  statusCode: 500,
  body: { message: "Server error" },
});

cy.visit("/products");
cy.contains("Something went wrong").should("be.visible");

Dynamic Test Data

Generate unique emails with timestamp in test to avoid collisions. cy.task runs Node code for database seeding and cleanup beyond browser sandbox.

Factory functions in support/helpers create objects combining faker or casual data with required invariants.

// cypress.config.ts
on("task", {
  seedUser(email) {
    return db.insertUser(email);
  },
});

cy.task("seedUser", "test+1782644135300@example.com");

Fixture Strategy

Version fixtures with API schema changes. Prefer minimal fixtures containing only fields UI uses—large payloads slow tests.

Separate fixtures for empty states, single item, many items, and error payloads for comprehensive UI coverage.

  • Commit fixtures to git for reproducible CI
  • Sync fixture shape with OpenAPI or TypeScript types in CI check
  • Avoid secrets in fixtures—even fake looking tokens confuse scanners

Get In Touch


Ready to discuss your next project? Drop me a message.