Manuals / Cypress / Ch 5

B · CoreIntermediate65 min read

5. cy.intercept — stub, spy, and wait

Cypress · 48 pages source format

Network control separates junior from mid-level Cypress. Stub slow or flaky APIs, simulate errors, and assert request payloads — without leaving the browser.

What you'll learn

  • Route matching
  • Aliases @getItems
  • Stub vs spy
  • Fixture responses

Spy on GET

cy.intercept("GET", "/inventory.json").as("getInventory"); cy.wait("@getInventory") ensures data loaded before assert.

Do this now

Add intercept + wait to inventory test. Assert 6 items render after @getInventory.

Clear?

Stub a failure

Force 500 on POST checkout. Assert error toast or message — UI resilience test.

cy.intercept("POST", "/checkout", { statusCode: 500, body: { error: "Server error" } }).as("checkoutFail");
// ... trigger checkout ...
cy.wait("@checkoutFail");
cy.get("[data-test=error]").should("be.visible");

Do this now

Stub checkout POST with statusCode: 500. Assert user-visible error.

Clear?

Fixture stub

Serve static JSON from fixtures/ for consistent test data regardless of backend state.

Do this now

Stub GET /inventory with fixture inventory-small.json (2 items). Assert UI shows 2.

Clear?

When to stub vs real API

Happy path: real API when stable. Edge cases and error UI: stub. Document policy in NETWORK.md.

Do this now

Write NETWORK.md: 3 rules for when your suite stubs vs hits real backend.

Clear?

Checklist