I have a NextJS application that uses Auth0 for authorization. I am trying to write Cypress tests for e2e testing, but I am having trouble with logging in via Auth0. I have followed the documentaion on Cypress Documentation for both "Login with cy.origin()" and "programmatic login". Both of these have given me two bugs that I can't get around.
Programmatic login:
Here is my definition of the custom command
/// <reference types="cypress" />
import jwt from 'jsonwebtoken'
Cypress.Commands.add('loginByAuth0Api', (username: string, password: string) => {
cy.log(`Logging in as ${username}`)
const client_id = Cypress.env('TENANT_CLIENT_ID')
const client_secret = Cypress.env('TENANT_CLIENT_SECRET')
const audience = Cypress.env('TENANT_AUDIENCE')
const scope = 'openid email profile'
cy.request({
method: 'POST',
url: `${Cypress.env('TENANT_DOMAIN')}/oauth/token`,
body: {
grant_type: 'password',
username,
password,
audience,
scope,
client_id,
client_secret
}
}).then(({ body }) => {
const claims = jwt.decode(body.id_token)
const { nickname, name, picture, updated_at, email, email_verified, sub, exp } = claims
const item = {
body: {
...body,
decodedToken: {
claims,
user: {
nickname,
name,
picture,
updated_at,
email,
email_verified,
sub
},
audience,
client_id
}
},
expiresAt: exp
}
window.localStorage.setItem('auth0Cypress', JSON.stringify(item))
})
})
declare global {
namespace Cypress {
interface Chainable {
loginByAuth0Api(email: string, password: string): Chainable<void>
}
}
}
export {}
Here is my implementation of the command, and the cypress test that is run:
describe('Auth0', () => {
it('should login', () => {
cy.loginByAuth0Api(Cypress.env('TENANT_EMAIL'), Cypress.env('TENANT_PASSWORD'))
cy.visit('localhost:3000/')
})
})
export {}
The issue that I am having, is that the application's session is not set. When cypress visits localhost:3000/, it should display the page, but if a user is not logged in (i.e. there is not active session), then it gets redirected to /login. When the test is run, cypress redirects to /login, which should not happen.
Login with cy.origin():
When logging in with cy.origin(), cypress redirects to the login page as well. However, if I get cypress to click on the sign in button again, it will go the correct page! This seems good at first, but when clicking around on other pages, the session is not actually set.
Thank you for your time