简体   繁体   中英

Adding basic auth to all requests in Cypress

I'm a Cypress newbie and need to add basic auth to all cy.visit() calls. The auth credentials are dependent on the deployment (ie they are specific to the 'baseUrl' which we set in the environment config files).

Currently, I have;

cy.visit("/", {
  auth: {
    username: '...',
    password: '...'
  }
});

What I want is to move the 'auth' object to the evg config files so I only need cy.visit("/") in the specs.

Many thanks

If you plan to reuse the authentification then is better to create a separate method for authentication eg:

1. Create a new custom command in `cypress/support/commands.js, since it is loaded before any test files are evaluated via an import statement in your supportFile (cypress/support/index.js by default).

Cypress.Commands.add('login', () => {
    // (you can use the authentification via API request)
    return cy
        .request({
            method: 'POST',
            url: your_url,
            form: true,
            body: {
                username: Cypress.env('username'),
                password: Cypress.env('password'),
                grant_type: 'password',
                client_id: your_clientId,
                client_secret: your_clientSecret,
                scope: 'openid',
            },
        })
})

2. Then use it in your test:

describe('My Test Name', () => {

    before(() => {
        cy.login();
    });

    it('should visit my base URL', () => {
        cy.visit('/');
    });
});

Note 1: Check how to set the environment variables here: Cypress.io: Environments Variables

Note 2: Check how to use the custom commands here: Custom Commands - Correct Usage

EDIT: since your syntax is correct - I will just share a way I use to do it in my tasks.

If your auth is working correctly you can make custom command - visitAndAuthorise like this for example:

Cypress.Commands.add("shopAdmin_visitAndLogin", (url) => {
    cy.log('shopAdmin_visitAndLogin')
    cy.visit(url)
    cy.get('[data-qa="emailInput"]')
        .type(Cypress.env('credentials').email)
    cy.get('[data-qa="passwordInput"]')
        .type(Cypress.env('credentials').password)
    cy.get('[data-qa="loginButton"]')
        .click()
    cy.get('[data-qa="logOutButton"]')
        .should('be.visible')
})

And your cypress.env.json file would need to include an object for the credentials like this:

{
   "credentials": {
      "email": "myEmail@gmail.com",
      "password": "myPassword"
   }
}

Or following your syntax:

Cypress.Commands.add("shopAdmin_visitAndLogin", (url) => {
    cy.log('shopAdmin_visitAndLogin')
    cy.visit(url, {
auth: {
    username: Cypress.env('credentials').username,
    password: Cypress.env('credentials').password
  }})
})

If you have HTTP basic auth for all pages add this code to your cypress/support/commands.js :

Cypress.Commands.overwrite('visit',  (originalFn, url, options) => {

options = options || {}

options.auth = {
  username: 'replace_this_with_the_username',
  password: 'replace_this_with_the_password'
}

return originalFn(url, options);
});

This is how I handled Basic Auth with Cypress using cy.request:

cy.request({
        method:'POST',
        url:'myURL',
        body: {
            Name: name,
            userId: userId,
            languageId: languageId
          },
          headers: {
            authorization: 'Basic lasdkfjlsdyZHRoYXRpa25vdzp'
          },
    }).then(response => {
       expect(response.status).to.equal(201)
        })
    })

Basically, the "headers" object inside the cy.request do the magic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM