Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share variable values in Cypress

I am learning to use Cypress. At this time, I have several spec files, structured as follows:

/cypress
  /integration
    /child-a
      list.spec.js
      item.spec.js
    /child-b
      list.spec.js
      item.spec.js
    index.spec.js

When a test run begins, I want to set a value, once. That value is coming from a web api. For that reason, I do not want to set that value before every single test. I also don't want to set it for every file. Instead, I only want to set it once. I then want to use that value in all of the tests ran in all of the spec.js files.

Is there a way to do this in Cypress? Kind of like a beforeAll or beforeSession? Or is there some other recommended way? The closest I saw was the [before][2] hook. Thank you.

like image 362
user687554 Avatar asked Feb 28 '26 09:02

user687554


1 Answers

I had a similar question, but I wanted that variable to be dynamic. For example, I wanted the test user I was creating to have a date in its email, like [email protected].

To do that and re-use it through all the tests I wanted to use the following code, but couldn't use a fixture since JSON isn't executable:

test+${new Date().getTime()}@example.com

I found the cypress/support/index.html useful (but I think you can initialize the variables in the specs too). By adding the following line to the file I was able to reuse that dynamic variable everywhere in my tests and it was unique to each cypress run.

// support/index.js
//...

Cypress.config('email', `test+${new Date().getTime()}@example.com`)

And then in my tests

Cypress.config('email')
like image 176
Sean Avatar answered Mar 03 '26 02:03

Sean