Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

cypress screen

like image 553
Kayote Avatar asked Aug 16 '26 08:08

Kayote


1 Answers

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

like image 110
Ashley Whitmore Avatar answered Aug 17 '26 22:08

Ashley Whitmore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!