Q20 of 48 · Cypress

Explain how cy.fixture() works and when to use it vs cy.intercept stubbing.

CypressMidcypressfixturesinterceptstubbingmid

Short answer

Short answer: `cy.fixture('file')` loads a JSON/CSV/text file from `cypress/fixtures/` into your test. Combine with `cy.intercept` to stub network responses with fixture data. Fixtures shine for static, reusable test data; `cy.intercept` with inline bodies shines for one-off or computed responses.

Detail

cy.fixture(filename) reads from cypress/fixtures/, returning the parsed contents (JSON parsed, others as text). It's a Cypress command, so it's queued — chain with .then to use the result.

The two primary uses:

As a payload for cy.intercept:

cy.intercept('GET', '/api/cart', { fixture: 'cart-with-3-items.json' });

Cypress reads the fixture and uses it as the response body. This is the cleanest way to stub a stable response shape — the fixture file is checked into git, named, and reused across tests.

As an input value:

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

When to prefer fixtures:

  • Response is static and shared across multiple tests.
  • The data is non-trivial (50+ lines of JSON).
  • You want non-engineers (e.g., PMs, product designers) to read it.

When to prefer inline cy.intercept bodies:

  • One-off response, used in a single test.
  • The body needs to be computed at test time (timestamps, IDs).
  • You want the assertion data and the stub data side-by-side in the spec for readability.

A common hybrid: load a fixture, modify it for the specific test:

cy.fixture('cart').then((cart) => {
  cart.total = 99.99;
  cy.intercept('GET', '/api/cart', cart);
});

// EXAMPLE

cypress/fixtures/cart-with-3-items.json

{
  "items": [
    { "id": "p1", "name": "Apples", "qty": 2, "unitPrice": 1.50 },
    { "id": "p2", "name": "Bread", "qty": 1, "unitPrice": 2.20 },
    { "id": "p3", "name": "Cheese", "qty": 1, "unitPrice": 4.80 }
  ],
  "subtotal": 10.00,
  "shipping": 2.50,
  "total": 12.50,
  "currency": "GBP"
}

// WHAT INTERVIEWERS LOOK FOR

Knowing fixtures are the storage layer, that `cy.intercept` is the network layer, and the hybrid pattern of loading + modifying.

// COMMON PITFALL

Putting fixtures in random folders — Cypress only reads from `cypress/fixtures/` by default.