Search code examples
typescriptcypress

How to hide fetch and XHR logs in Cypress 12?


I'm learning Cypress 12 and wanted to disable fetch and XHR from logging. In my research, I found "Hide XHR calls on Cypress test runner" which points to this gist but for some reason, it's not working.

My following steps:

root level tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": [
      "cypress",
      "node",
      "cypress-real-events",
      "cypress-file-upload",
      "cy-verify-downloads"
    ],
    "baseUrl": "./"
  },
  "include": ["**/*.ts", "./cypress/support/cypress.d.ts"]
}

directory tree of:

/ 
  tsconfig.json
  package.json
  yarn.lock
  cypress.config.ts
  / cypress
    / support
      / cypress.d.ts
      / e2e.ts

contents of cypress.d.ts:

declare namespace Cypress {
  interface ResolvedConfigOptions {
    hideXHRInCommandLog?: boolean;
  }
}

contents of e2e.ts:

// Hide fetch/XHR requests from command log
if (Cypress.config('hideXHRInCommandLog')) {
  const app = window.top;
  if (
    app &&
    !app.document.head.querySelector('[data-hide-command-log-request]')
  ) {
    const style = app.document.createElement('style');
    style.innerHTML =
      '.command-name-request, .command-name-xhr { display: none }';
    style.setAttribute('data-hide-command-log-request', '');

    app.document.head.appendChild(style);
  }
}

still renders the XHR:

enter image description here

this appears to be a known issue from further research:

In Cypress 12 how can I hide XHR and fetch logs?


Solution

  • You can use an intercept at the top of the test to turn off logging for fetch and xhr.

    cy.intercept({ resourceType: /xhr|fetch/ }, { log: false })
    

    See RouteMatcher

    resourceType - The resource type of the request. See "Request object properties" for a list of possible values for resourceType.

    {
      ...
      resourceType: 'document' | 'fetch' | 'xhr' | 'websocket' | 'stylesheet'
                 | 'script' | 'image' | 'font' | 'cspviolationreport' | 'ping'
                 | 'manifest' | 'other'
    }