【问题标题】:Passing a same random number to all tests in Cypress将相同的随机数传递给赛普拉斯的所有测试
【发布时间】:2020-07-31 16:35:55
【问题描述】:

所以我有两个测试 - Test1.spec.js 和 Test2.spec.js,我希望每次测试运行时都应该生成一个随机数,并且应该在两个规范中使用相同的随机数。我在 support/index.js

下为此编写了一个简单的 Math.random() 函数
Cypress.config('UniqueNumber', `${Math.floor(Math.random() * 10000000000000)}`)

在测试中我写的是:

cy.get('locator').type(Cypress.config('UniqueNumber'))

当我尝试使用 cypress 应用程序 npm cypress open 执行测试,然后运行所有规范时,会生成一个随机数,并将相同的数字正确传递给两个规范文件。但是,当我尝试使用 CLI npx cypress run 为两个规范文件运行测试时,传递了不同的随机数。

如果使用 CLI 执行测试,我做错了什么?

【问题讨论】:

    标签: javascript random config cypress npx


    【解决方案1】:

    因此,根据cypress docs support/index.js 每次运行每个规范文件之前都会运行,所以我的上述方法无效,因为每次运行都会生成一个新值。所以我遵循的下一个方法是在第一次测试时将值写入 fixtures/data.json 文件中,并在整个测试中使用它。这样,每次运行都会生成一组新值并将其保存在夹具文件中,然后在整个测试套件中为该测试运行使用相同的值。以下是我写入 fixtures/data.json 文件的方式:

        const UniqueNumber = `${Math.floor(Math.random() * 10000000000000)}`
    
        cy.readFile("cypress/fixtures/data.json", (err, data) => {
            if (err) {
                return console.error(err);
            };
        }).then((data) => {
            data.username = UniqueNumber
            cy.writeFile("cypress/fixtures/data.json", JSON.stringify(data))
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 2021-10-20
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多