In Cypress, how do I stub a POST API request with parameters in the body?

Viewed 8970

I am writing an end-to-end test with Cypress and I would like to stub the network requests which my application makes. Specifically, I would like to stub out multiple POST requests which have parameters in the body and to change my simulated response based on those parameters.

I would like to do something like

cy.route({
  method: "POST",
  url: "/todos/add"
  params: {
    "urgency": 3,
    "stakeholder_id": "SKH001"
  },
  response: "fixture:add1.json",
})

cy.route({
  method: "POST",
  url: "/todos/add"
  params: {
    "urgency": 1,
  },
  response: "fixture:add2.json",
})

But after reading through https://docs.cypress.io/guides/guides/network-requests.html and https://docs.cypress.io/api/commands/route.html#Arguments, I do not see a supported way of checking the arguments in the request being stubbed.

Can I accomplish this by passing a function to the onRequest parameter of cy.route? If so, what would I return from that function which tells cypress "this route actually does not handle this request"?

4 Answers
cy.route({
  method: "POST",
  url: "/todos/add"
  body: {
    "urgency": 1,
  },
  response: "fixture:add2.json",
})

You can use intercept method too.

cy.intercept('POST', <your api end point>, {response:
<your json file path>}).as('postAPI')
Related