Cypress - 为所有XHR请求添加自定义头部

9
我注意到在测试期间,所有来自被测应用程序的XHR请求都会删除X-CSRFToken头。我已经通过Cypress.Cookies.preserveOnce('sessionid', 'csrftoken')保存了Cookies,但不确定如何保留这个头部信息。
因此,我考虑将自定义头部X-CSRFToken附加到应用程序的所有XHR请求中。以下是我使用的脚本,其中我从Cookies中获取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>'.

我期望得到任何解决这个方法的工作方案或更好的解决方案。
4个回答

9

现在 cy.server 已经弃用,你可以使用 cy.intercept 代替:

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

更多信息请参阅文档


1
非常完美,谢谢!您可以选择将“'GET'”或“'POST'”设置为第一个参数。 - user3025289

5

4

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

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

cy.server已经过时了:/ - user3025289

0

我也尝试通过 onRequest,但是从Gleb Bahmutov先生那里听到的是,@cypress目前不支持此功能。 - Kondasamy Jayaraman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接