如何在 Cypres.io 中使用 cy.intercept 操作任何路由和请求类型?

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

之前 Cypress 6.0.0, I was using the cy.server() 在任何 request 上设置 request header 像这样:

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

然后在 beforeEach 挂钩中调用它,如下所示:

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

现在,我正在使用 Cypress 6.5.0 & I'm trying to accomplish the same functionality with cy.intercept 方法,如下所示:

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

这不起作用,尽管 if no HTTP method is defined Cypress will match all requests by default

您应该使用 ***/* 而不是 /*,前导斜线不适用于最小匹配。