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

笑着哭i 提交于 2020-06-27 08:05:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!