Skip to content

API Testing with Cypress — Intercept, Stub, and Assert Network Requests

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about API Testing with Cypress. We cover key concepts, practical examples, and best practices to help you master this topic.

Cypress provides built-in network interception through cy.intercept() to stub API responses, assert outgoing requests, and verify API behavior without leaving the browser test context.

What You'll Learn

  • How to intercept and stub API responses with Cypress
  • Asserting request payloads and response data
  • Combining API tests with E2E browser tests

Why It Matters

Frontend tests depend on APIs. By stubbing API responses, tests become fast, deterministic, and independent of backend availability while still validating that the frontend handles API data correctly.

Real-World Use

A dashboard application loads user data from an API. Cypress tests stub the response to simulate different user roles (admin, viewer, blocked) and verify the UI renders the correct controls for each role.

flowchart LR
    A[Cypress Test] --> B[cy.intercept]
    B --> C[Stub Response]
    C --> D[Browser Request]
    D --> E[Assert UI]
    D --> F[Assert API Call]

Stubbing a GET Response

Intercept a GET request and return custom data.

describe("Product List", () => {
  it("displays products from API", () => {
    cy.intercept("GET", "/api/products", {
      statusCode: 200,
      body: [
        { id: 1, name: "Laptop", price: 999 },
        { id: 2, name: "Mouse", price: 29 },
      ],
    }).as("getProducts");

    cy.visit("/products");
    cy.wait("@getProducts");
    cy.get(".product-card").should("have.length", 2);
    cy.contains("Laptop").should("be.visible");
  });
});

Expected output: The page renders two product cards with correct names.

Asserting Request Payloads

Verify that the frontend sends the correct data to the API.

describe("Create User", () => {
  it("sends correct user data", () => {
    cy.intercept("POST", "/api/users").as("createUser");

    cy.visit("/users/new");
    cy.get("#name").type("Alice");
    cy.get("#email").type("alice@example.com");
    cy.get("button").contains("Save").click();

    cy.wait("@createUser").then((interception) => {
      expect(interception.request.body).to.deep.equal({
        name: "Alice",
        email: "alice@example.com",
      });
      expect(interception.response.statusCode).to.equal(201);
    });
  });
});

Expected output: The test verifies the exact request payload and status code.

Testing Error Handling

Stub error responses and verify the UI shows appropriate messages.

describe("Error Handling", () => {
  it("shows error message on 500", () => {
    cy.intercept("GET", "/api/products", {
      statusCode: 500,
      body: { error: "Internal server error" },
    }).as("getProductsError");

    cy.visit("/products");
    cy.wait("@getProductsError");
    cy.contains("Something went wrong").should("be.visible");
    cy.get(".retry-button").should("exist").click();
  });
});

Expected output: The page displays an error message and a retry button.

Common Mistakes

Mistake Why It's Wrong
Not using as() for interception aliases Tests become unreadable without named intercepts
Stubbing without waiting Tests race ahead before the API call is intercepted
Forgetting to test both stub and real API Stubs hide backend bugs; always run integration tests too
Over-mocking Stubbing every call makes tests unrealistic
Not resetting intercepts between tests Intercepts persist and affect unrelated tests
Asserting on response before wait The interception object is undefined before cy.wait()
Ignoring Graphql operation names Intercept GraphQL by operation name in the request body

Practice Questions

  1. What does cy.intercept() do? A: Listens for and optionally modifies HTTP requests made by the browser during a Cypress test.
  2. How do you stub a GraphQL mutation in Cypress? A: Use cy.intercept("POST", "/graphql", (req) => { if (req.body.operationName === "AddUser") { ... } }).
  3. What is the difference between cy.intercept() and cy.route()? A: cy.route() is deprecated. cy.intercept() uses the Fetch API layer and supports all request types.
  4. How do you simulate a network delay in Cypress? A: Use req.reply() with a delay: req.reply({ delay: 3000, body: data }).
  5. How do you verify a request was NOT made? A: Use a negative assertion or check intercept count: cy.get("@apiCall").should("not.exist").

Challenge

Write Cypress tests for a todo app that: intercepts GET /todos and returns 5 todos, intercepts POST /todos and verifies the payload, stubs a 500 error on DELETE /todos/1 and verifies error UI, stubs a network delay and verifies a loading spinner appears, and asserts that clicking "Add" sends the correct todo text.

FAQ

Can Cypress test APIs without a browser?

Yes, use cy.request() for direct API testing without rendering a page.

How do you test authentication flows with Cypress?

Use cy.setCookie() or cy.request() to obtain a token, then set it before visiting the app.

What is the difference between cy.intercept() and cy.request()?

cy.intercept() captures browser-initiated requests; cy.request() makes direct HTTP requests.

How do you test file upload APIs in Cypress?

Use cy.fixture() to load a file and cy.intercept() to stub the upload endpoint.

Can Cypress test Websocket connections?

Cypress does not natively support WebSocket interception, but you can use cy.stub() on the WebSocket constructor.

How do you wait for multiple API calls?

Use cy.wait() with an array of aliases: cy.wait(["@api1", "@api2"]).

What is the best practice for API base URLs?

Store the base URL in cypress.config.js and use environment variables for different environments.

Mini Project

Build a Cypress test suite for a React product management app. Test: product list loads and displays cards (stub 10 products), create product sends correct POST payload, update product sends correct PUT payload, delete product removes card and calls DELETE, 500 error shows error toast, and 401 redirects to login. Use cy.intercept() for all API calls.

What's Next

Next, learn API test automation best practices to structure and maintain your test suites effectively.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro