Ask Your Question

Revision history [back]

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.