Matt
Matt

Reputation: 501

Cypress Inserting an already authenticated token

I have an application to test that requires MFA. I am trying to get my UI tests through Cypress to hit the application already authenticated.

I've seen a few posts about setting up a new Cypress command to handle logging in where it sends auth details to the 3rd party, gets the details back and puts this into local storage using something like cy.setLocalStorage.

But I already have an external method that I use for my API tests where it grabs me a valid Bearer token. This works fine for API calls on the application. So I'm wondering, is there a place I can simply insert this valid token for my UI tests with Cypress or do I need to go the kind of way as defined in the linked article below where I build a cy.login() command?

Edit: Should add that we actually have a service principal account for the API calls to bypass MFA.

https://auth0.com/blog/end-to-end-testing-with-cypress-and-auth0/

Upvotes: 2

Views: 5327

Answers (2)

Fody
Fody

Reputation: 31862

You can also add session caching to the login command, or a wrapper command for your external method that grabs the token.

The request is only fired once, then the results are cached so the same token is restored each time you call the command.

Cypress.Commands.add('login', (username, password) => {
  cy.session([username, password], () => {
    cy.request({
      method: 'POST',
      url: '/login',
      body: { username, password },
    }).then(({ body }) => {
      window.localStorage.setItem('authToken', body.token)
    })
  })
})

Upvotes: 2

Sebastiano Schwarz
Sebastiano Schwarz

Reputation: 1146

Without having more information about the exact login and your application, if the token for your API tests is the same and sufficient for the login, then you can probably store it in the local or session storage depending on where your app is looking for the valid token.

The only important thing then is that you do this before the first cy.visit command to show your app that you are already authenticated / logged in like:

describe('Your Test', () => {
  it('Login and page visit', () => {
    // or sessionStorage.setItem()
    localStorage.setItem('your_token_name', yourToken);
    cy.visit('your app url')
  })
})

However, I'm not sure if the MFA requires additional login steps that you might not cover with it. If in doubt, you can also think about disabling MFA for a test user used in your Cypress tests.

Besides that, as you've already written, it's often a good way to log in via request to avoid having to test third-party UIs that you have no control over changing, such as here an example for Azure AD Login.

Upvotes: 3

Related Questions