Passing variable in several js files using Cypress

Viewed 239

For Cypress tests I am setting up an email adress in a js file. Then I would like to use this variable in another file. With import/export it runs the entire script from the previous file, I only need the variable

3 Answers

You can move your email value to /cypress/support/index.js and import into both tests.

Or define a custom command in /cypress/support/commands.js and avoid having to import it.

// cypress/support/commands.js

Cypress.Commands.add('getEmail', () => 'random@gmail.com')
// all tests

cy.getEmail().then(email => {
  ...
})

Unfortunately that makes a simple variable asynchronous and you have to access it with .then().


Environment variables for static data

If the data is static, you can define it as an environment variable,

In Cypress V9

// cypress.json

{
  ...
  "env": {
    "email": "random@gmail.com",
  }
}

In Cypress V10

// cypress.config.js

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  projectId: '128076ed-9868-4e98-9cef-98dd8b705d75',
  env: {
    email: 'random@gmail.com',
  }
})
// all tests
const email = Cypress.env('email')

Actually, in Cypress v10 the config is now a javascript file so you should be able to set email via a function

// cypress.config.js

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  projectId: '128076ed-9868-4e98-9cef-98dd8b705d75',
  env: {
    getEmail: () => { 
      return 'random@gmail.com';
    },
  }
})
// all tests
const email = Cypress.env('getEmail')()  // invoke the function

You should be able to use a named export to avoid running the tests in the exporting file.

export const email = ...
import {email} from ...

Possible solution using Fixtures:

support/commands.js:

Cypress.Commands.add('generateFixtureEmail', () => {

cy.writeFile('cypress/fixtures/email.json', {
    'hits':Cypress._.times(1, () => {
        let randomNumber= Math.floor(Math.random() * 1001);
        const email ='random+'+randomNumber+'@mail.com';
        return {
            'Email': email

        }
    })
})

a json file is made: fixtures/email.json

"hits": [
{
  "Email": "random+475@mail.com"
}

]

support/index.d.ts:

declare namespace Cypress {
interface Chainable<Subject = string> {
    generateFixtureEmail(): Chainable<Element>;
}

integration/test-scripts/test.js:

describe('Test', function()
  {
         before(() => {
            cy.generateFixtureEmail()

            cy.fixture('email').then(function (data) {
                this.data = data;
                 })

                       })


    it('testcase 1', function () { cy.loginWithEmail(this.data.hits[0].Email)

note: do not commit the generated json file

Related