简体   繁体   中英

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. 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'))

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM