我注册并登录了一个用户,但是,在测试中,当我导航到身份验证后面的页面时,赛普拉斯失败,并带我回到登录页面。从外观上看,before
函数已成功执行(由API日志验证)。这是我的代码:
describe("Dashboard page", () => {
before(() => {
cy.fixture("authUserRegistrationDetail.json").then(userDetail => {
cy.fixture("authUserLoginDetail.json").then(userLoginDetail => {
cy.visit("http://localhost:3000/login");
cy.get(".cookieConsent button").click();
// create a random email for registration
userDetail.email = `${Math.random()
.toString(36)
.slice(-5)}@aaa.aaa`;
// share the email between userLogin & userRegistration obj
userLoginDetail.email = userDetail.email;
// register the user
cy.request("POST", "http://localhost:9000/users/", userDetail)
.its("body")
// login the same user
cy.request("POST", "http://localhost:9000/api-token-auth/", userLoginDetail).then($res => {
cy.request({
url: "http://localhost:9000/loggedinuser/",
headers: {
Authorization: `Token ${$res.body.token}`
}
});
});
});
});
});
// run the test
it("visits the dashboard...", () => {
cy.visit("http://localhost:3000/dashboard/");
cy.get("h2").contains("Your deals");
});
});
运行代码后,测试将在断言时失败,并且用户未登录。这是测试结果的屏幕截图。当用户注册然后登录时,我得到的状态码为200。为什么用户登录名不能持久保存在测试中,并且仪表板链接失败。
编辑: 我只是意识到我正在以编程方式登录,但是,一旦登录,我如何才能使Cypress浏览器识别状态变化和用户已登录。即,如何刷新Cypress屏幕以识别用户登录?
答案 0 :(得分:2)
从上面的代码看,您登录后似乎并没有保留cookie。赛普拉斯会在每次测试之前自动清除所有cookie,以防止建立状态。您应该能够执行以下操作:
before(() => {..cy.login() })
beforeEach(() => {
Cypress.Cookies.preserveOnce('session_id', 'remember_token')
})
此柏树doco应该提供更多上下文usage