将相同的随机数传递给赛普拉斯中的所有测试

Passing a same random number to all tests in Cypress

所以我有两个测试 - 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 然后 运行 All Specs 执行测试时,会生成一个随机数并将其正确传递给两个 spec 文件。但是,当我尝试 运行 使用 CLI npx cypress run 对两个规范文件进行测试时,会通过不同的随机数。

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

所以根据 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))
    })
})