访问 get in then 块的输出

access the output of get in then block

如何在 .then() 函数中访问从 .get().contains() 生成的元素

我的代码没有进入 Then 块。我哪里做错了?

cy.get(".c-header-listItem").contains("My Account").should(($link) => {
        expect(localStorage.read("CD-SessionId")).to.be.not.null;`enter code here`
    }).then(($link) => {
        $link.click();
    });

我从赛普拉斯文档中获得了登录信息https://docs.cypress.io/api/commands/should.html#Subjects

.should(elem => {}) 的行为与 .then(elem => {}) 完全相同,除了传递给 should 的函数将重试,直到它不抛出任何异常。考虑到这一点,以下代码应该可以工作:

cy.get(".c-header-listItem").contains("My Account").should(($link) => {
    expect(localStorage.read("CD-SessionId")).to.be.not.null;

    // Notice I have to wrap this to perform a Cypress 
    // click on it. $link is a native DOM object.
    cy.wrap($link).click();
});

这也可以,但没有必要进行分离。

cy.get(".c-header-listItem").contains("My Account").should(($link) => {
    expect(localStorage.read("CD-SessionId")).to.be.not.null;
});

cy.get(".c-header-listItem").contains("My Account").click();