mercredi 20 novembre 2019

Cypress login using request method

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");
        userDetail.email = `${Math.random()
          .toString(36)
          .slice(-5)}@aaa.aaa`;
        userLoginDetail.email = userDetail.email;
        cy.request("POST", "http://localhost:9000/users/", userDetail)
          .its("body");
        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 and the user is not logged in. Here is the screenshot of the test result. Why is the user login not persisting in the tests & the dashboard link fails.

Aucun commentaire:

Enregistrer un commentaire