Javascript 将相同的随机数传递给Cypress中的所有测试

Javascript 将相同的随机数传递给Cypress中的所有测试,javascript,random,config,cypress,npx,Javascript,Random,Config,Cypress,Npx,所以我有两个测试-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(

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

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

因此,在每次运行spec文件之前,都会运行support/index.js
,因此我的上述方法无效,因为每次运行都会生成一个新值。因此,我遵循的下一种方法是在第一次测试时将值写入fixtures/data.json文件,并在整个测试过程中使用它。这样,每次运行都会生成一组新的值并保存在fixture文件中,然后在整个测试套件中为该测试运行使用相同的值。下面是我如何写入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))
    })
})
因此,在每次运行spec文件之前,都会运行persupport/index.js,因此我的上述方法无效,因为每次运行都会生成一个新值。因此,我遵循的下一种方法是在第一次测试时将值写入fixtures/data.json文件,并在整个测试过程中使用它。这样,每次运行都会生成一组新的值并保存在fixture文件中,然后在整个测试套件中为该测试运行使用相同的值。下面是我如何写入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))
    })
})