赛普拉斯使用请求方法登录 [英] Cypress login using request method

查看:163
本文介绍了赛普拉斯使用请求方法登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注册&登录用户,但是,在我的测试中,当我导航到身份验证后面的页面时,赛普拉斯将失败&带我回到登录页面。从它的外观看, before 函数已成功执行(由API日志验证)。这是我的代码:

I register & login a user, however, when in my test I navigate to a page behind authentication, Cypress fails & takes me back to the login page. From the looks of it, the before function is successfully executed (as verified by the API log). Here is my code:

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然后登录。为什么用户登录名不保留在测试&中?仪表板链接失败。

Once the code is run, the test fails on assertion and the user is not logged in. Here is the screenshot of the test result. I get a status code 200 when user signs up & then logs in. Why is the user login not persisting in the tests & the dashboard link fails.

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

推荐答案

从上面的代码来看,登录后似乎并没有保留cookie。赛普拉斯会自动清除每次测试前所有cookie都将阻止状态的建立。您应该能够执行以下操作:

From the above code, it doesn't look like you are preserving the cookie once logged in. Cypress automatically clears all cookies before each test to prevent state from building up. You should be able to do something similar to this:

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

beforeEach(() => {
    Cypress.Cookies.preserveOnce('session_id', 'remember_token')
})

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

This cypress doco should provide more context https://docs.cypress.io/api/cypress-api/cookies.html#Preserve-Once

这篇关于赛普拉斯使用请求方法登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆