【问题标题】:Cypress - Add custom header for all XHR requestsCypress - 为所有 XHR 请求添加自定义标头
【发布时间】:2019-03-01 04:06:19
【问题描述】:

我注意到 X-CSRFToken 标头在测试之间被删除,对于从被测应用程序触发的所有 XHR 请求。我不确定是否保留此标头,因为我已经通过 Cypress.Cookies.preserveOnce('sessionid', 'csrftoken') 保留了 Cookies

因此,我想将自定义标头 X-CSRFToken 附加到来自应用程序的所有 XHR 请求中。这是我使用的脚本,我从 cookie 中获取 csrftoken 并设置为自定义标头。

cy.server({
   onAnyRequest: function(route, proxy) {
        proxy.xhr.setRequestHeader('X-CSRFToken', cy.getCookie('csrftoken'));
   }
})

在这里,我收到以下错误,

Argument of type '{ onAnyRequest: (route: any, proxy: any) => void; }' is not assignable to parameter of type 'Partial<ServerOptions>'.
  Object literal may only specify known properties, and 'onAnyRequest' does not exist in type 'Partial<ServerOptions>'.

我期待这种方法的任何可行解决方案或更好的解决方案。

【问题讨论】:

    标签: javascript typescript testing cypress


    【解决方案1】:

    现在cy.server 已弃用,您可以改用cy.intercept

    cy.intercept('http://api.company.com/', (req) => {
      req.headers['authorization'] = `token ${token}`
    })

    更多信息请关注docs

    【讨论】:

    • 完美运行,谢谢!或者,您可以设置例如'GET''POST' 作为第一个参数。
    【解决方案2】:

    为了让大家知道,我与Cypress的制造商进行了沟通,并了解到传出请求的存根正在开发中,可以在-https://github.com/cypress-io/cypress/issues/687下进行跟踪

    【讨论】:

      【解决方案3】:

      在 beforeEach 语句中运行您的代码。

      beforeEach(() => {
          cy.server({
              onAnyRequest: function(route, proxy) {
                 proxy.xhr.setRequestHeader('X-CSRFToken', cy.getCookie('csrftoken'));
             }
          })
      });
      

      【讨论】:

      • cy.server 已弃用:/
      【解决方案4】:

      我认为您正在寻找 onRequest 而不是 onAnyRequestHere's the documentation for cy.server options

      【讨论】:

      • 我也通过onRequest 完成了。但是,我从 Gleb Bahmutov 先生那里听到的是,这个功能目前在 @cypress 中不可用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 2012-06-16
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多