Cypress login using request method

China☆狼群 提交于 2019-12-11 15:50:20

问题


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");
  });
});

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.

EDIT: I just realised that I am programmatically logging in, however, once logged in, how do I get Cypress browser to recognise the change in state & that the user is logged in. I.e, how do I refresh the Cypress screen to recognise the the user login?


回答1:


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')
})

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



来源:https://stackoverflow.com/questions/58959223/cypress-login-using-request-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!