'How to return HTTP response body from Cypress custom command?

I am trying to write a custom Cypress command that sends a POST request to an endpoint, & I then want to store the response body in my test.

Here is what the response body looks like in Postman:

enter image description here

Here is my custom command in cypress/support/commands.js, for simplicity, I've removed the request body values:

Cypress.Commands.add('createStudent', (email) => {
    cy.request({
        method: `POST`,
        url: `myUrl`,
        body: {}
      }).then((resp) => {
        return resp
      });
});

Here is the code in my spec file:

let response = cy.createStudent(email);
cy.log(response)

However, when I run the code I get back the below object rather than the response body:

enter image description here

Can someone please tell me where I am going wrong, & what changes are required to return the actual HTTP response body?



Solution 1:[1]

If you'll only ever be using the value in a Cypress chain, you could simply alias the command.

Cypress.Commands.add('createStudent', (email) => {
    cy.request({
        method: `POST`,
        url: `myUrl`,
        body: {}
      }).as('student');
});
...
cy.createStudent();
cy.get('@student').then((response) => {
  cy.log(response.body) // assuming you'd want to log the response body.
});
// OR
cy.get('@student').its('body').should('eq', { foo: 'bar' });
// the above example doesn't work with logging, but I'm guessing you don't _just_ want to log the response

If you may need the variable at other times outside of a Cypress chain, you could always stash the variable in Cypress.env().

Cypress.Commands.add('createStudent', (email) => {
    cy.request({
        method: `POST`,
        url: `myUrl`,
        body: {}
      }).then((res) => {
          Cypress.env('student', res);
      });
});
...
cy.createStudent().then(() => {
  cy.get('foo').should('have.text', Cypress.env('student').body.foo);
});
// key point is referencing the entire response by `Cypress.env('student')`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1