'Cypress basic authentication in all cy.visit requests

I have a cy.visit() calls with basic authentication which looks like this:

it('launch website', () => {
  cy.visit('url', {
  auth: {
    username: '....',
    password: '....',
  },
 })

And it works fine. But in order to make this code more useable, I dont want to hard code my credentials in every test, but I want to create a command so every time I visit that page, it uses my basic auth. I tried to implement solutions from Adding basic auth to all requests in Cypress , but it didnt work for me. It doesnt accept credentials that are stored in command. file. Any ideas other then those already mentioned?

Many thanks :)



Solution 1:[1]

You can use Cypress custom commands for this.

  1. Go to cypress/support/commands.js and wrte:
Cypress.Commands.add('authenticateUrl', (url, user, pass) => {
  cy.visit(url, {
    auth: {
      username: user,
      password: pass,
    },
  })
})
  1. In your test you can just write this. You can pass url, username and passwords as parameters.
cy.authenticateUrl('https://example.com', 'admin', 'pass123')

In case you don't want to use paramters, you can directly harcode url, username and password inside the custom command.

Cypress.Commands.add('authenticateUrl', () => {
  cy.visit('https://example.com', {
    auth: {
      username:'admin',
      password:'pass123',
    },
  })
})

In your test just use:

it('launch website', () => {
  cy.authenticateUrl() //Launch URL and authenticate
})

Solution 2:[2]

This can be avoided by overwriting the visit function. Add this to cypress/support/index.js

Cypress.Commands.overwrite('visit', (originalVisit, url) => {
    originalVisit(url, {
        auth: {
            username: 'username',
            password: 'password'
        }
    })
});

Notice that this code only working with cy.visit(url). If you pass another arguments you should change it according to your situation.

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
Solution 2 Andrey Nelubin