通过 API 会话登录后,我在 UI 中注销。我使用自定义命令进行登录,并在 beforeEach 挂钩内的步骤定义之一中重用它。我不确定我在这里做错了什么,但它没有按预期工作。
//command.js
const platform = Cypress.env("platform");
Cypress.Commands.add("loginViaAPI", (user, pass) => {
cy.session([user, pass], () => {
cy.request({
method: "POST",
url: "/login",
body: {
username: user,
password: pass
}
}).then(res => {
expect(res.status).to.eq(200)
window.localStorage.setItem("token", JSON.stringify(res.body))
})
},
{
validate() {
cy.visit("/home")
}
}
)
})
//Step Definition
beforeEach(function () {
cy.loginViaAPI(platform.admin_username, platform.password);
cy.visit(platform.host);
});
Given("...", () => {
cy.visit("/home");
});
When("...", () => {
*does something*
})
Then("...", () => {
*does something*
});```
值得尝试
cy.window()
而不是window
。该应用程序在 iframe 中运行,因此它会看到不同的 window
对象,可通过 cy.window()
访问该对象。
.then(res => {
cy.window().then(win => {
expect(status)...
win.localStorage.setItem("token", JSON.stringify(res.body)
})
})