Cypress.io: Is is possible to set global variables in Cypress and if yes; how?

12,355

Solution 1

this can be done more easily than that : in your cypress.json add

"env": {
   "YourVarName":"YourVarValue"
}

And in your code you can access to your var with :

const myGolabalVar = Cypress.env("YourVarName")

That's all you need

Solution 2

I recently found the answer in another blog on github linked here: https://github.com/cypress-io/cypress/issues/1121

But the answer in this blog was answered my Brian Mann with...

"TL;DR - just use modules, not globals.

Cypress is just JavaScript. All of the underlying principles about structuring files apply to Cypress as it would your own application files.

In this case, you keep mentioning variables. Variables are things defined in a particular file and are never global. This means it's not possible for them to be shared. Variables are accessible based on the local scope in which they are defined.

In order to make them global you have to attach them to a global object: window. However, there's no reason to do this, Cypress automatically has module support built in. This enables you to import functions into each spec file, thus making them way more organized and obvious than using globals.

We have recipes of this here: https://docs.cypress.io/examples/examples/recipes.html#Node-Modules"

I hope this helps someone else who is on Stackoverflow for this answer!

Solution 3

You can use the cypress.json file and set enviornment values there. If you do not want to use .env values, then you create any constants file you like and import it in to via the cypress index.js file.

Create a constants file, e.g., cypress/constants.js with a json object inside:

    export const constants = {
  VALUEA: 'my text for value A',
  VALUEB: 'example value b'
}

in support/index.js add a reference to your constants.js file:

import '../constants';

This will automatically import the constants dictionary into all of your spec files.

All you have to do to reference your constants in your spec files, is to use "constants.VALUEA" for example:

cy.get('#button-label-id).should('contain.text', constants.VALUEB);
Share:
12,355
smunizaga
Author by

smunizaga

Updated on June 07, 2022

Comments

  • smunizaga
    smunizaga almost 2 years

    I am trying to set a global variable (NOT A GLOBAL ENV VARIABLE) in Cypress.io. I would like to abstract a url that I will use over and over again AND something that I can use in multiple files (not just one).

    Also, I do not want to set it as baseurl. I already have that set and I want to leave that alone.

    Can anyone help me with this?

  • João Melo
    João Melo about 3 years
    Thank you very much for researching the answer. Still, I would like to inject some globals constants like the cypress tool already appears to do with "cy", "describe", "it" and so on.