Cypress: capture and log all XHR requests to a file

597 views Asked by At

Using Cypress to test a web app, I have tests failing because of an unexpected XHR response from our test backend.

The screenshots and screencasts doesn't help understanding why we get this error message from the webapp. It would be very useful to get the actual XHR requests logs as an artifact.

It seems to be possible to capture some routes using cy.route, but it seems to be more suitable to stub requests.

What is the correct way to capture and write the XHR logs alongside the screenshots and videos ? It would be even better if it would delete the file if everything passes.

1

There are 1 answers

0
Artsem Dzerauniuk On

To record the network traffic in the same manner like the network tab in devtools, you can utilize the HAR file format (http://www.softwareishard.com/blog/har-12-spec/). To generate a HAR file during the execution of your Cypress tests you can use the cypress-har-generator plugin.

describe('my tests', () => {
  before(() => {
    // start recording
    cy.recordHar();
  });

  after(() => {
    // save the HAR file
    cy.saveHar({ waitForIdle: true });
  });

  it('does something', () => {
    cy.visit('https://example.com');

    // ...
  });
});

It will save a HAR that can be used to inspect the network activity, identify the performance issues or troubleshooting bugs. The file can be skimmed using any kind of viewer (e.g. https://developer.chrome.com/blog/new-in-devtools-76/#HAR).