【问题标题】:Adding basic auth to all requests in Cypress向赛普拉斯中的所有请求添加基本身份验证
【发布时间】:2021-05-14 09:48:03
【问题描述】:

我是赛普拉斯新手,需要为所有 cy.visit() 调用添加基本身份验证。 身份验证凭据取决于部署(即它们特定于我们在环境配置文件中设置的“baseUrl”)。

目前,我有;

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

我想要将“auth”对象移动到 evg 配置文件中,所以我只需要在规范中使用 cy.visit("/")

非常感谢

【问题讨论】:

  • 您要授权什么?我们需要这些信息才能提供帮助。 - 用户凭据?网址?页面元素?
  • @RosenMihaylov 抱歉,我已经更新了问题以使其更清晰,这是我想通过“访问”请求发送的用户名和密码。

标签: authentication testing cypress


【解决方案1】:

如果您打算重用身份验证,那么最好创建一个单独的身份验证方法,例如:

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


describe('My Test Name', () => {
  
  before(() => {
     cy.login(); 
  });

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

注意1:在这里查看如何设置环境变量:Cypress.io: Environments Variables

注意2:在这里查看如何使用自定义命令:Custom Commands - Correct Usage

【讨论】:

    【解决方案2】:

    编辑:因为你的语法是正确的 - 我将分享我在我的任务中使用的一种方式。

    如果您的 auth 工作正常,您可以制作自定义命令 - 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')
    })
    

    而且您的 cypress.env.json 文件需要包含一个用于凭证的对象,如下所示:

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

    或者按照你的语法:

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

    【讨论】:

      猜你喜欢
      • 2019-02-27
      • 2022-11-02
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 2017-04-04
      • 2021-11-19
      相关资源
      最近更新 更多