Search code examples
integration-testingcypress

Cypress: How to access the body of a POST-request?


Is there a way in Cypress to check the body of a POST-request?

E.g.: I have entered some data in a form, then pressed "Submit". The form-data is send via POST-request, separated by a blank line from the header-data.

I would like to check the form-data. If all data, which I have entered, are included and if they are correct.

Is that possible with Cypress?

cy.get('@login').then(function (xhr) {
    const body = xhr.requestBody;
    console.log(xhr);
    expect(xhr.method).to.eq('POST');
});

The xhr-object doesn't have the transferred data included.


Solution

  • It should be possible.

    describe('Capturing data sent by the form via POST method', () => {
      before(() => {
        Cypress.config('baseUrl', 'https://www.reddit.com');
        cy.server();
        cy.route({
          method: 'POST',
          url: '/login'
        }).as('redditLogin');
      });
      it('should capture the login and password', () => {
        cy.visit('/login');
        cy.get('#loginUsername').type('username');
        cy.get('#loginPassword').type('password');
        cy.get('button[type="submit"]').click();
    
        cy.wait('@redditLogin').then(xhr => {
          cy.log(xhr.responseBody);
          cy.log(xhr.requestBody);
          expect(xhr.method).to.eq('POST');
        })
      });
    });
    

    This is how you can inspect your data in Chrome Developer Tool.

    This is how you can inspect your data in Chrome Developer Tool

    You should see the same thing you've seen from Chrome Developer Tool when you run your test in Cypress.

    You should see the same thing you've seen from Chrome Developer Tool when you run your test in Cypress