javascript - Cypress 保存 cookie 值

标签 javascript node.js cypress

我想使用 Cypress 保存 cookie 值,但不幸的是我总是在使用此代码的日志控制台中得到未定义

let cookieValue;
cy.getCookie('SOME_COOKIE')
    .should('have.property', 'value')
    .then((cookie) => {
        cookieValue = cookie.value;
    })
cy.log(cookieValue);

当我尝试这个时

let cookieValue;
cy.getCookie('SOME_COOKIE')
    .should('have.property', 'value', 'Dummy value')
    .then((cookie) => {
        cookieValue = cookie.value;
    })
cy.log(cookieValue);

我可以在错误消息中看到我想要的实际值。

最佳答案

Cypress 异步工作,您无法像以前那样使用 cookie 值。

来自the docs

Want to jump into the command flow and get your hands on the subject directly? No problem, simply add a .then() to your command chain. When the previous command resolves, it will call your callback function with the yielded subject as the first argument.

您应该在 then 回调中继续执行测试代码,而不是依赖外部 let cookieValue 赋值。

试试这个

cy.getCookie('SOME_COOKIE')
    .should('have.property', 'value')
    .then((cookie) => {
        cookieValue = cookie.value;
        // YOU SHOULD CONSUME `cookieValue` here
        // .. go ahead inside this `then` callback
    })

关于javascript - Cypress 保存 cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55168418/

相关文章:

javascript - window.event.srcelement 在 Firefox 中不工作

javascript - 正则表达式:通过一次匹配捕获多个可选组

javascript - 使用 nvidia GPU 在 Windows x64 上的 Chrome 中 Webgl 闪烁

node.js - Sequelize Express 示例 - 为什么 fs.readdirSync 没有重复调用?

javascript - 使用 Node Selenium 下载 Excel 文件

javascript - 如何检查在 Cypress e2e 测试中元素是否永远不可见?

javascript - Angular 1.5 组件访问 ui-router $state

javascript - 通过 Node.js 控制台获取用户输入

Cypress :如何识别元素是否仅包含数字

typescript - 如何在不运行测试的情况下编译 Cypress TypeScript