Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Last active September 5, 2024 07:13
Show Gist options
  • Save simenbrekken/3d2248f9e50c1143bf9dbe02e67f5399 to your computer and use it in GitHub Desktop.
Save simenbrekken/3d2248f9e50c1143bf9dbe02e67f5399 to your computer and use it in GitHub Desktop.
Hide fetch/XHR in Cypress command log

This novel workaround simply hides any command log entries that originate from fetch/XHR requests.

While I've updated this receipe for Cypress 10 and converted it to TypeScript you should be able to use it in a JavaScript project by ignoring the cypress.d.ts file and placing the snippet from e2e.ts in e2e.js instead.

// Add the following to cypress/support/cypress.d.ts
declare namespace Cypress {
interface ResolvedConfigOptions {
hideXHRInCommandLog?: boolean;
}
}
// Add the following to cypress/support/e2e.ts or cypress/support/e2e.js
// 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);
}
}
@landtechjoe
Copy link

We had a similar situation but where we only wanted to hide xhr requests to specific domains so went a slightly different route on the workaround that handles each individual logged message. It's not quite so clean maybe but suited our specific purpose.

Cypress.on("log:added", (ev) => {
  if (ev.displayName === "xhr" && /some-domain/.test(ev.consoleProps.URL)) {
    const el = Array.from(window.top.document.querySelectorAll(".command-wrapper")).slice(-1)[0];
    if (el) {
      el.style.display = "none";
    }
  }
});

@cie
Copy link

cie commented May 10, 2022

This worked for me:

const origLog = Cypress.log
Cypress.log = function (opts, ...other) {
  if (
    opts.displayName === 'fetch' &&
    opts.url.startsWith("https://example.com")
  ) {
    return
  }
  return origLog(opts, ...other)
}

@Aravinth-Earth
Copy link

It just works, Thanks for sharing :)

@LaxmiMaddali
Copy link

@simenbrekken this throws an error as object is possibly null how do i fix this please

Copy link

ghost commented Jun 1, 2022

This no longer works since I updated to Cypress 10.0. The support/index.js file was renamed to support/e2e.js , Would that be the reason as to why?

@Zwimber
Copy link

Zwimber commented Jun 5, 2022

The solution of @cie works nicely in the latest version 10.0.2.

It's also really easy to modify to do even more advanced things, thanks for the tip! Slightly modified if you want to block certain domains:

const cypressLogOriginal = Cypress.log
const cypressLogDomainsHidden = ['fontawesome.com']
Cypress.log = function (opts, ...other) {
	const logFetchIs = ['fetch'].includes(opts.displayName)
	const logFetchDomainMatch = logFetchIs && cypressLogDomainsHidden.find((d) => opts.url.includes(d))
	if (logFetchDomainMatch) return
    
	return cypressLogOriginal(opts, ...other)
}

@simenbrekken
Copy link
Author

I haven't had time to update to 10, but @cie appears to be working.

@drecali
Copy link

drecali commented Jun 23, 2022

@justjoshn I just updated to 10.2.0 and @simenbrekken's snippet still works for me. If you used the Cypress.config('hideXHR') option there might be a problem with the placement of your hideXHR config value in the newly generated cypress.config.ts file.

Thanks again @simenbrekken for such a useful snippet!

@simenbrekken
Copy link
Author

simenbrekken commented Sep 24, 2022

I've now updated this for Cypress 10 with TypeScript: https://gist.github.com/simenbrekken-visma/e804c86fd6a23cc59b89913eabbf1d82

@NishanthKR5
Copy link

Thanks @simenbrekken, snippet works like a charm (currently in 11.2.0)

@craigsumner
Copy link

Very helpful thread.
I landed on:

/**
 * @see https://gist.github.com/simenbrekken/3d2248f9e50c1143bf9dbe02e67f5399
 */
export function silenceFetchLogs(silenceFetchPattern: RegExp | string): void {
  let loggedOnce: boolean = false;
  const originalCypressLog = Cypress.log
  Cypress.log = function (opts, ...other) {
    if (
      opts.displayName === "fetch"
      &&
      ((opts as any).url as string).match(silenceFetchPattern) != null
    ) {
      if (loggedOnce) {
        return
      } else {
        loggedOnce = true;
        opts.displayName = "noisy fetch - will be silenced";
        return originalCypressLog(opts, ...other)
      }
    }
    return originalCypressLog(opts, ...other)
  }
}

@laudi2204
Copy link

laudi2204 commented Jun 7, 2023

Perfect! Works like a charm.

Thank you!

@shikder-klikit
Copy link

thanks a lot

@Yevhen-Nistratov
Copy link

A slightly easier way of disabling, using cy.intercept():
in your './cypress/support/e2e' set:

before(function () {
    // disable Cypress's default behavior of logging all XMLHttpRequests and fetches to the Command Log
    cy.intercept({ resourceType: /xhr|fetch/ }, { log: false })
})

@Brugui7
Copy link

Brugui7 commented Jul 14, 2023

Based on this thread I created a cypress plugin to filter logs both with cypress open and cypress run based on log levels.

You can check it out here: https://www.npmjs.com/package/cypress-log-filter

@elycruz
Copy link

elycruz commented Jul 25, 2023

Based on this thread I created a cypress plugin to filter logs both with cypress open and cypress run based on log levels.

You can check it out here: https://www.npmjs.com/package/cypress-log-filter

This library would've been great if didn't permit the log messages' markup to render at all (in my scenario I have many requests coming in, almost never ending, which causes the host OS to run out of memory (which just causes cypress to crash)).

Nevermind comment - Just realized your plugin is for filtering ('live') but not necessarily preventing the markup rendering.

Thanks for sharing!

@Brugui7
Copy link

Brugui7 commented Jul 26, 2023

Based on this thread I created a cypress plugin to filter logs both with cypress open and cypress run based on log levels.
You can check it out here: https://www.npmjs.com/package/cypress-log-filter

This library would've been great if didn't permit the log messages' markup to render at all (in my scenario I have many requests coming in, almost never ending, which causes the host OS to run out of memory (which just causes cypress to crash)).

Nevermind comment - Just realized your plugin is for filtering ('live') but not necessarily preventing the markup rendering.

Thanks for sharing!

Yeah, the thing is that I tried filtering them before they were added in the first place but the logs API doesn't allow you to do that :'(

That's as much as I was able to do

@elycruz
Copy link

elycruz commented Aug 2, 2023

👍 , I hear you - In the end I went with the "shimming the Cypress.log method approach (mentioned by @cie), but more refined (used a regular expression, defined outside of custom method, and just ran a test on incoming log displayName types).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment