Make Cypress Intercept Responses Dynamic


Here's how to make cypress intercepts return dynamic responses.

Mock Network Responses

Cypress allows you to do functional testing in a browser. You can intercept network requests that you want to mock. Any request matching such a pattern will return the mocked response. But there may be times that you want a non-default response to come back. You can make cy.intercept return a dynamic value, perhaps based on a calculation in code.

Method 1: Function

You can make the return dynamic by passing a callback function to cy.intercept as the 2nd argument. Here's a function that returns a new generated id on each request:

import { v4 as uuid } from 'uuid'

cy.intercept({
  method: "POST",
  url: "**/api/upload/stuff/**",
}, req => {
  req.reply(res => {
    res.send({ statusCode: 201, body: { entries: [{ id: uuid() }] }})
  })
})

This is dynamic and compact and works for infinite calls.

Method 2: Multiple Calls

The second method is to call intercept multiple times.

// once
cy.intercept(
  {
    method: "POST",
    url: "**/api/upload/stuff/**",
    times: 1
  },
  {
    statusCode: 201,
    body: { entries: [{ id: uuid() }] }
  }
)

// twice
cy.intercept(
  {
    method: "POST",
    url: "**/api/upload/stuff/**",
    times: 1
  },
  {
    statusCode: 201,
    body: { entries: [{ id: uuid() }] }
  }
)

Here, we enumerate every all. It's more declarative. Only do this for a handful of calls.