使用请求方法登录Cypress

Kay*_*ote 3 javascript testing e2e-testing cypress

我注册并登录用户,但是,当在测试中导航到身份验证后面的页面时,Cypress 失败并将我带回登录页面。从表面上看,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");
  });
});
Run Code Online (Sandbox Code Playgroud)

代码运行后,测试断言失败,用户未登录。这是测试结果的屏幕截图。当用户注册然后登录时,我收到状态代码 200。为什么用户登录在测试中没有持续存在并且仪表板链接失败。

编辑:我刚刚意识到我正在以编程方式登录,但是,一旦登录,我如何让赛普拉斯浏览器识别状态变化以及用户已登录。即,如何刷新赛普拉斯屏幕以识别用户登录?

柏木屏风

小智 5

从上面的代码来看,您似乎并没有在登录后保留 cookie。Cypress 在每次测试之前会自动清除所有 cookie,以防止状态建立。您应该能够执行类似的操作:

before(() => {..cy.login() })

beforeEach(() => {
    Cypress.Cookies.preserveOnce('session_id', 'remember_token')
})
Run Code Online (Sandbox Code Playgroud)

这个 cypress doco 应该提供更多上下文https://docs.cypress.io/api/cypress-api/cookies.html#Preserve-Once

  • 这些只是示例 cookie 名称,与您的代码无关。 (3认同)