How to login programatically in Cypress E2E test using Next Auth JWT

212 views Asked by At

I want to login programmatically using Cypress. Login Through UI Works but I can't figure it out how to login programmatically.

import { signIn, signOut, useSession } from "next-auth/react";

// Login Form.
const handleSubmit = async (event: any) => {
    event.preventDefault();
    try {
      await signIn("credentials", {
        email: email,
        password: password,
        redirect: false,
      });
    } catch (error) {
      console.error("Error", error);
    }
  };

Command to login programatically I followed next-auth REST API docs Command I receive 200 success message but it won't login.

Cypress.Commands.add("loginPR", (email, password) => {
  cy.request("GET", "/api/auth/csrf").then((csrfResponse: any) => {
    const csrfToken = csrfResponse.body.csrfToken;
    cy.request("POST", "/api/auth/signin/credentials", {
      email,
      password,
      csrfToken,
    }).then((loginResponse) => {
      expect(loginResponse.status).to.equal(200);
    });
  });

  return cy.wrap(null);
});

Error message

Here's the github repository

  1. Most important files are commands.ts and login.cy.ts
  2. Currently test is logging through UI. To test programatically update login.cy.ts
    // Working Example:
    // cy.loginUI("[email protected]", "kflsdfklsdfk");
    // cy.get('[data-testid="loggedInUser"]');

    // DOES NOT WORK
    cy.visit("/");
    cy.loginPR("[email protected]", "kflsdfklsdfk");
    cy.reload();
    cy.get('[data-testid="loggedInUser"]');
  1. To run Cypress npm run cypress:open
  2. Any email or password will login user.
0

There are 0 answers