[英]Passing a same random number to all tests in Cypress
So I have two tests - Test1.spec.js and Test2.spec.js and I want that with every test run a random number should be generated and the same random number should be used in both the specs.所以我有两个测试——Test1.spec.js 和 Test2.spec.js,我希望每次测试运行时都应该生成一个随机数,并且在两个规范中都应该使用相同的随机数。 I wrote a simple
Math.random()
function for this under support/index.js我在support/index.js下为此写了一个简单的
Math.random()
function
Cypress.config('UniqueNumber', `${Math.floor(Math.random() * 10000000000000)}`)
And in the tests I am writing as:在我写的测试中:
cy.get('locator').type(Cypress.config('UniqueNumber'))
When I am trying to execute the tests using the cypress app npm cypress open
and then Run All Specs, a random number is generated and the same is passed to both of the spec files correctly.当我尝试使用赛普拉斯应用程序
npm cypress open
然后运行所有规范来执行测试时,会生成一个随机数,并将相同的数字正确传递给两个规范文件。 But when I try to run the tests using the CLI npx cypress run
for both of the spec files different random numbers are passed.但是,当我尝试使用 CLI
npx cypress run
为两个规范文件运行测试时,会传递不同的随机数。
What am I doing wrong in case of executing the tests using CLI?如果使用 CLI 执行测试,我做错了什么?
So as per cypress docs support/index.js is run every time before each spec file is run, so my above approach is not valid because with every run a new value would be generated.因此,根据cypress docs support/index.js每次运行每个规范文件之前都会运行,所以我的上述方法无效,因为每次运行都会生成一个新值。 So the next approach I followed was to write the values in the fixtures/data.json file on the first test and use it throughout the tests.
所以我遵循的下一个方法是在第一次测试中将值写入fixtures/data.json文件并在整个测试中使用它。 This way with every run a new set of values would be generated and saved in the fixture file and then the same value would be used throughout the test suite for that Test Run.
这样,每次运行都会生成一组新值并将其保存在夹具文件中,然后在整个测试套件中为该测试运行使用相同的值。 Below is the way how I wrote to fixtures/data.json file:
以下是我写入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))
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.