This blog post is continuation of the Avoid Cypress Pyramid of Doom blog post where we extracted two numbers from the page and then compared their sum to the result shown on the page. My final solution was to use beforeEach
hook and aliases to write the test.
1 | describe('Use beforeEach hook and number values', () => { |
🎁 You can find the source code for this blog post in the repo bahmutov/cypress-multiple-aliases.
Possible solutions
Hmm, but what if getting the values from the application is complicated? We don't want to put the logic into the beforeEach
hook. Instead we want to write two tests: one test to get the numbers, another test to confirm the displayed sum:
1 | it('has two number inputs', () => { |
This approach introduced a dependency between the tests. You always have to run the first test before running the second one. Let's say we can live with this. How do we pass the actual values a
and b
? Hmm, we cannot use in the second test aliases set in the first test; all aliases are reset before each test.
1 | // 🚨 INCORRECT, NOT GOING TO WORK |
We could store values found in the first test in the variables in the common scope
1 | // will work, if both tests can access a and b |
I don't like this approach. Each variable requires boilerplate code and can easily be modified by any code in between.
Use Cypress.env
Here is an alternative approach: use the Cypress.env()
object. You can synchronously set and get values from this object from any place in your tests (even outside the tests).
1 | // set "name: Joe" |
The entire Cypress.env
object is reset when the spec starts running. Thus any values we put there remain there until the spec is re-run
1 | // when spec starts, Cypress.env only has |
We can pass values without declaring each variable. In our spec
1 | describe('pass value from one test to another', () => { |
Cypress-map
I have a collection of Cypress query commands for Cypress v12+ in my plugin cypress-map. I have cy.asEnv
query command that you can use to save the current subject in the Cypress.env
object.
1 | # install the plugin |
Here is the updated spec file
1 | import 'cypress-map' |
If you click on the command "asEnv
1 | it('has values set', () => { |