Reputation: 2458
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"?
Upvotes: 13
Views: 11180
Reputation: 1
Here is an example for you using intercept. https://docs.cypress.io/api/commands/intercept#Arguments
const handler = (req) => {
if (req.body.urgency === 3) {
req.reply({
statusCode: 200,
fixture: `your fixture`,
})
};
if (req.body.urgency === 1) {
req.reply({
statusCode: 200,
fixture: `your other fixture`,
})
};
}
cy.intercept('POST', yourURLMatcher, handler)
Upvotes: 0
Reputation: 36
If your Cypress version is greater than 6, you should refactor to use intercept
. Intercept handles params really cleanly and you can assign parts of output to a file using the alias or in the callback.
https://docs.cypress.io/api/commands/route https://docs.cypress.io/api/commands/intercept#Arguments
Upvotes: 1
Reputation: 393
You can use intercept method too.
cy.intercept('POST', <your api end point>, {response:
<your json file path>}).as('postAPI')
Upvotes: 0
Reputation: 2458
One option is to use Mirage.js
https://miragejs.com/docs/comparison-with-other-tools/#cypress-route-mocks
See their tutorial: https://miragejs.com/quickstarts/cypress/
Upvotes: 0
Reputation: 1
cy.route({
method: "POST",
url: "/todos/add"
body: {
"urgency": 1,
},
response: "fixture:add2.json",
})
Upvotes: 0