'Cypress: I want run tests in 100 spec files by login one time and persist login for every file. Is it possible?

I have almost 100 specs files including multiple tests. I want run all these specs files by login one time. I dont want my cypress should login process every time on every spec file It it possible to persist single login for all spec files



Solution 1:[1]

Take a look at our "Logging in" recipes https://github.com/cypress-io/cypress-example-recipes#logging-in-recipes - most of them log in once using before hook, and then save the cookie / token in a local variable and set it again and again in beforeEach hook

Solution 2:[2]

This is the recommend approach that Cypress.io suggest you use, as this is quite the anti-pattern.

Cypress Docs

Anti-Pattern: Sharing page objects, using your UI to log in, and not taking shortcuts.

Best Practice: Test specs in isolation, programmatically log into your application, and take control of your application’s state.

You should have one spec file/few tests that do actually test your login screen/functionality, to confirm that is does indeed work.

But then any other time you should programmatically log into your account via an API and store the credentials in a cookie or token.

That way you should be able to bypass the login screen.

Once you have the API working you can add it into a before hook in the appropriate place.

Solution 3:[3]

This is easily possible if you use the login before all tests, and after that, you have to set up cookies by default. I did this inside cypress/support/index.ts because it loads first.

before(() => {
    cy.yourLoginHook()
})
 
Cypress.Cookies.defaults({
    preserve: 'yourCookie',
})

Solution 4:[4]

If someone else will have similar problem or Kashif is still interested I think i have solution.

You can wrap the each test (whole file also should work) inside your spec files into "export function" and use them in an other spec file that will be processed with cypress IDE.

utils.spec.ts:

export function loginTestName(){
  describe('Test Preparation', () => {
    it('Application login', () => {
      ...
    })
  })
}

test.spec.ts

loginTestName()
otherFunction()
describe('Other functions', () => {

  it('Add user', () => {
    ...
  })
})

Just be aware that when you warp test into export function, it won't be detected as a test by Cypress, so you need to remove them from "integration test localization" and reuse them in another file after moving.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gleb bahmutov
Solution 2 cchapman
Solution 3 Manuel Abascal
Solution 4 S?awek Skrzypczak