【问题标题】:How to read data from JSON file and use it in Cypress test如何从 JSON 文件中读取数据并在 Cypress 测试中使用它
【发布时间】:2021-06-04 17:57:24
【问题描述】:

我正在为不同类型的用户编写登录测试,并且我有一个 JSON 文件,其中包含不同用户的用户凭据。

[
    { 
        "userType":"admin,
        "email":"admin@test.com",
        "password":"test1234"
    },
    { 
        "userType":"employee,
        "email":"employee@test.com",
        "password":"test1234"
    }
]

这些是我的测试:

it('Login test - admin user', () => {
    cy.get("[type='email']").type('admin@test.com');
    cy.get("[type='password']").type('test1234');
    cy.get("[id='login']").click();
    cy.url().should('includes', '/dashboard');
});

it('Login test - employee user', () => {
    cy.get("[type='email']").type('employee@test.com');
    cy.get("[type='password']").type('test1234');
    cy.get("[id='login']").click();
    cy.url().should('includes', '/welcome');
});

我想传递用户类型并获取用户的凭据并在测试中使用它。有可能吗?

【问题讨论】:

    标签: typescript cypress


    【解决方案1】:

    我遇到了类似的问题,这是我的方法。这不是您的用例的确切解决方案,因为我的 .txt 文件中的数据需要一些拆分,您可以使用 JSON.parse() 轻松调整它:

    1. 创建一个新的custom command,我们称之为getUser,它将使用task
    Cypress.Commands.add("getUser", () => {
        return cy.task("getUser").then((user) => {
            return user;
        });
      });
    
    1. plugins/index.js 中定义新的getUser 任务:
    const fs = require('fs')
    var users = []
    var usersLoaded;
    
    module.exports = (on, config) => {
      on('task', {
        getUser(){
          if (!usersLoaded && fs.existsSync("<<path>>/users.txt")) {
            var usersFile = fs.readFileSync("<<path>>/users.txt", 'utf8')
            users = usersFile.split('\n');  //here you might need to adjust for json parsing
            usersLoaded = true;
          }
          return users.shift()
        }
    }
    

    注意使用的 usersLoaded 布尔值和 users 数组。基本上我加载了所有用户,然后从数组中一一弹出(使用array.shift())。

    1. 那么在你的测试中你可以使用
    cy.getUser().then((user) => {
      cy.log(user)
      //your code here
    })
    
    1. 您会遇到另一个问题:遍历用户以完成您的工作。为此,我的方法是:
    Cypress._.times(10, () => { //where 10 is the number of users you have in your file
      describe('Test', () => {
        it('Login ', () => {
          cy.getUser().then((user) => {
            //your code here
          })
        })
      })
    })
    

    我选择了这种方法,以便为每个用户进行不同的测试。缺点是您需要对用户数量进行硬编码。

    我不是柏树专家,这只是我的方法。可能有更聪明的方法来实现这一点。在研究了cypress RWA auth tests 使用类似cy.database("find", "users") 的东西之后,我基本上想出了这个。

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      相关资源
      最近更新 更多