3

How can I log a "request.body" from cypress interceptor. Here is the code

  beforeEach(() => {
    cy.log("---- -- Running beforeEach");
    cy.intercept("POST", "/graphql", (req) => {
      cy.log("-- --- -- loging from interceptor", req.body);
      return req;
    });
  });

I get this error :

Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.

If I remove cy.log no errors are raised. So how can I log this? This runs on CI.

Will use https://github.com/flotwig/cypress-log-to-output plugin if no other way.

Joylette
  • 88
  • 5
kevo
  • 31
  • 1
  • 3
  • I would try `req.continue()` instead of `return req` -- is there a specific reason you are returning the request? – agoff Jan 12 '22 at 14:23
  • either return or req.continue() the issue persists. It is the cy.log within the interceptor that is causing the error. – kevo Jan 12 '22 at 22:21

2 Answers2

3

One way you can access the request body would be using cy.should() callback as follows. First you define your intercept command and add an alias to it:

// intercept some post request
cy.intercept('POST', '/api/**').as('yourPostRequest');

After that, you append cy.should() with callback function to the cy.wait() command which allows you to access and log the request body like:

// wait and log request body
cy.wait('@yourPostRequest').should(($obj) => {
  const requestBody = $obj.request.body;
  cy.log(requestBody);
});

You can also find more helpful information regarding network calls and Cypress in this blog post.

Manfredi
  • 27
  • 5
Sebastiano Schwarz
  • 1,060
  • 2
  • 13
  • 32
3

You may be able to use the synchronous Cypress.log instead

cy.intercept("POST", "/graphql", (req) => {
  Cypress.log({ displayName: 'Request body', message: req.body })
  ...
})
Fody
  • 23,754
  • 3
  • 20
  • 37