Reputation: 101
I'm trying to access a const variable from another file. Here is the structure:
I have welcome.spec.js and here I've declared a const variable as below and exported it. I'm using the value for this spec.
context('Welcome', () => {
// Generating a random userCount value for further verifications.
const userCount = (Math.round(Math.random()*10))
module.exports = {userCount}
beforeEach(() => {
cy.visit('/')
cy.clearCookies()
})
I also have payments.spec.js where I need to use exactly the same value.
context('Payment', () => {
const {userCount} = require ('../welcome/welcome.spec')
beforeEach(() => {
cy.visit('/')
cy.clearCookies()
})
In several cases, I need to make some assertions depending on that randomly generated value. This structure works but not as I expected. Here is the result:
Under Payments, as you can see, it imports all my tests from Welcome as well. I have duplicate tests + randomly generated values are different between those 2 Welcome tests.
What I tried:
Moved const declaration out of context
.
Tried to create a custom command (../support/commands) but I got errors like userCount is not a function or userCount is not defined. Also, I tried to use index.js as well under Cypress' support folder.
How can I access that const variable from another file without duplicating my tests and with using the same value? How should I proceed? Is the way that I did the declaration and export wrong?
Note: According to the value ==> const userCount, on Welcome screen user enters this value and on Payments input fields are displayed according to that value. (3 users ==> 3 user info fields, etc.)
Thanks in advance! Regards.
Upvotes: 0
Views: 4371
Reputation: 1
You can save the variables into a fixture file: In Welcome.spec.js
// Generating a random userCount value for further verifications.
const userCount = (Math.round(Math.random() * 10))
context('setting test variables', () => {
it('Setting up test context', () => {
cy.writeFile('cypress/fixtures/test.json', {
"usercount": userCount
})
})
})
Then add your other code in there:
context('Welcome', () => {
beforeEach(() => {
cy.visit('/')
cy.clearCookies()
})
In payments.spec.js, you can then do this:
context('Payment', () => {
beforeEach(() => {
cy.fixture('test.json').then(data => {
cy.log(data.usercount)
// you can access your variable in the data object
})
cy.visit('/')
cy.clearCookies()
})
The fixture file can be used in any spec file once it is loaded.
This issue here explains how to keep dynamic variables between tests
Upvotes: 0
Reputation: 269
Export the const outside the context. This is how you can access it in the other file when you import it (ES6).
welcome.spec.js
const userCount = (Math.round(Math.random()*10))
context('Welcome', () => {
// Generating a random userCount value for further verifications.
module.exports = {userCount}
beforeEach(() => {
cy.visit('/')
cy.clearCookies()
})
payments.spec.js
import {userCount} from "../welcome/welcome.spec";
Upvotes: 1