javascripthttprequestcypressintercept

How to manipulate any route & request type with cy.intercept in Cypres.io?


Previously to Cypress 6.0.0, I was using the cy.server() to set a request header on any request like so:

Cypress.Commands.add('setHeaderToken', () => {
  cy.server({
    onAnyRequest: (route, proxy) => {
      proxy.xhr.setRequestHeader('<CUSTOM-HEADER-HERE>', '<header-value-here>')
    },
  })
});

Then calling it in the beforeEach hook like so:

beforeEach(() => {
  cy.setHeaderToken();
});

Now, I'm using Cypress 6.5.0 & I'm trying to accomplish the same functionality with cy.intercept method like so:

Cypress.Commands.add('setHeaderToken', () => {
  cy.intercept('/*', (req) => {
    req.headers['<CUSTOM-HEADER-HERE>'] = '<header-value-here>'
  });
});

This is not working, despite if no HTTP method is defined Cypress will match all requests by default.


Solution

  • You should use * or **/* instead of /*, the leading slash does not work with minimatch.