Šahen Bdojan
Šahen Bdojan

Reputation: 23

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 :)

Upvotes: 0

Views: 2448

Answers (2)

Andrey Nelubin
Andrey Nelubin

Reputation: 3294

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.

Upvotes: 2

Alapan Das
Alapan Das

Reputation: 18618

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
})

Upvotes: 3

Related Questions