将相同的随机数传递给赛普拉斯的所有测试 [英] Passing a same random number to all tests in Cypress

查看:61
本文介绍了将相同的随机数传递给赛普拉斯的所有测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. I wrote a simple Math.random() function for this under support/index.js

Cypress.config('UniqueNumber', `${Math.floor(Math.random() * 10000000000000)}`)

在测试中,我的写作方式是:

And in the tests I am writing as:

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

当我尝试使用cypress应用程序 npm cypress open 然后执行运行所有规格"来执行测试时,会生成一个随机数,并且该随机数会正确地传递到两个规格文件中.但是,当我尝试使用CLI为两个规范文件使用 npx cypress run 运行测试时,会传递不同的随机数.

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. 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执行测试,我该怎么办?

What am I doing wrong in case of executing the tests using 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. 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. 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:

    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))
    })
})

这篇关于将相同的随机数传递给赛普拉斯的所有测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆