【问题标题】:environment variable uncontrolled update环境变量不受控制的更新
【发布时间】:2022-01-15 00:22:59
【问题描述】:

我目前正在尝试以动态方式处理 cy.request 标头。

为此,我在环境变量中设置了默认标头,如果特定请求需要,我会附加其他标头。

问题是在请求结束时,环境变量会自动更新为本地头值。

这是我使用的代码:

function my_function(jSessionCookie) {
    // build header
    let header = Cypress.env("defaultAPIheader")
    console.log("default header = ", header) // (1)
    header["Connection"] = "keep-alive"
    header["Cookie"] = jSessionCookie
    console.log("header = ", header) // (2)
    return cy.request({
        method: 'GET',
        headers: header,
        url: '<my_url>',
        body: null,
        referer: '/rootapp/index.html',
        referrerPolicy: "strict-origin-when-cross-origin",
        failOnStatusCode: true
    }).its('body').then((body) => {
        Cypress.env("requestToken", body) // store for further use
        console.log("default header2 = ", Cypress.env("defaultAPIheader")) // (3)
        return body
    })
}

我从控制台看到的是:

(1) default header =  {Accept: 'application/json, text/plain, */*'}
(2) header = {Accept: 'application/json, text/plain, */*', Connection: 'keep-alive', Cookie: '<my_cookie>'} which is what I expect
(3) default header2 = {Accept: 'application/json, text/plain, */*', Connection: 'keep-alive', Cookie: '<my_cookie>'}

看起来环境变量已被本地值替换,但无法弄清楚它是如何发生的。

【问题讨论】:

    标签: environment-variables cypress


    【解决方案1】:

    一位同事发现了问题所在(谢谢罗宾!)。变量设置给出了参考而不是值。 为了避免我修改我的代码如下:

    let header = Cypress._.cloneDeep(Cypress.env("defaultAPIheader"))
    

    通过在文件开头设置const { _, $ } = Cypress,可以减少:

    let header = _.cloneDeep(Cypress.env("defaultAPIheader"))
    

    这不再修改我的环境变量。

    【讨论】:

      猜你喜欢
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 2015-06-12
      • 2017-09-08
      • 2019-07-01
      • 2020-06-06
      相关资源
      最近更新 更多