Ask Your Question
1

How can I create a stub for a POST API request with body parameters in Cypress?

asked 2021-12-03 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-06-25 19:00:00 +0000

huitzilopochtli gravatar image

To create a stub for a POST API request with body parameters in Cypress, you can use the cy.route() and cy.fixture() commands. Here's an example of how to do it:

cy.fixture('example.json').then((requestData) => {
  cy.route('POST', '/api/endpoint', requestData).as('postRequest')
})

// Interact with your app to trigger the API request...

cy.wait('@postRequest').then((xhr) => {
  expect(xhr.status).to.eq(200)
  expect(xhr.response.body).to.have.property('success', true)
})

In this example, example.json contains the data you want to send in the POST request body. The cy.fixture() command loads the data from the file and passes it to the cy.route() command, which creates a stub for the POST request to /api/endpoint with the specified data.

The cy.wait() command waits for the API request to complete, and the then() callback function checks that the response status is 200 and that the response body contains a success property with a value of true. You can modify this callback function to perform additional checks on the response as needed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-03 11:00:00 +0000

Seen: 16 times

Last updated: Jun 25 '21