简体   繁体   English

为赛普拉斯中的所有请求添加基本身份验证

[英]Adding basic auth to all requests in Cypress

I'm a Cypress newbie and need to add basic auth to all cy.visit() calls.我是赛普拉斯新手,需要为所有cy.visit()调用添加基本身份验证。 The auth credentials are dependent on the deployment (ie they are specific to the 'baseUrl' which we set in the environment config files).授权凭据取决于部署(即它们特定于我们在环境配置文件中设置的“baseUrl”)。

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.我想要的是将 'auth' object 移动到 evg 配置文件,所以我只需要cy.visit("/")在规范中。

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). 1. 在 `cypress/support/commands.js 中创建一个新的自定义命令,因为它是在通过 supportFile 中的 import 语句评估任何测试文件之前加载的(默认为 cypress/support/index.js)。

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: 2.然后在你的测试中使用它:

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注1:在此处查看如何设置环境变量: Cypress.io: Environments Variables

Note 2: Check how to use the custom commands here: Custom Commands - Correct Usage注意 2:在此处检查如何使用自定义命令: 自定义命令 - 正确用法

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:如果您的身份验证工作正常,您可以制作自定义命令 - visitAndAuthorise 像这样,例如:

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:并且您的 cypress.env.json 文件需要包含一个 object 的凭据,如下所示:

{
   "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 :如果您对所有页面都有 HTTP 基本身份验证,请将此代码添加到您的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 使用 Cypress 处理 Basic Auth 的方式:

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.基本上,cy.request 中的“标头”object 发挥了作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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