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);
});
Here's the github repository
- Most important files are commands.ts and login.cy.ts
- 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"]');
- To run Cypress
npm run cypress:open - Any email or password will login user.
