问题
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"?
回答1:
cy.route({
method: "POST",
url: "/todos/add"
body: {
"urgency": 1,
},
response: "fixture:add2.json",
})
回答2:
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/
来源:https://stackoverflow.com/questions/54161968/in-cypress-how-do-i-stub-a-post-api-request-with-parameters-in-the-body