Passing VARIABLE VALUES between tests in Cypress

Usage of cy.task() to pass variable values between Cypress tests..

Have you ever come across a situation where you need to pass a variable value across your Cypress tests? Still wonder how to do it properly?

You are lucky, I’m here to HELP :)

What I faced..

When I was automating an eCommerce web app using Cypress [AKA the Selenium Killer ;)], I came across a test scenario with the following:

  • Add few items to the cart in a test
  • Verify the total of all the items in the shopping cart on another test

So, what I have to do is when I’m adding an item to the cart I must save the price of the item from the product details page and then, in my next test retrieve the addition of the values and compare with the total in shopping cart page. Sounds simple right.. BUT IS IT???

For Your Information (FYI)

Normally you would test all those different parts in separate spec files. But if you already have created these specs, you can re-use those. All we have to do is store the output as state so that we can use it as input for another spec.

Behind Cypress, there runs a Node.js server process in the background. You can make use of Node and store temporary data there. You can even seed a test database if you like! As long as you don’t close the Cypress console, values from the last run persist here.

The Saviour.. cy.task()

With that said, using the cy.task() command you can pass a value to NodeJS. All you have to do is create a variable and write getter and setter commands. You know what getters and setters are? If yes, this is just a piece of cake ❤

Let’s get on with it..

Head over to the plugins > index.js file in your cypress project. Then create a variable and write the getters and setters like this:

This is how I wrote to calculate the total of items

Now you might be wondering how to access these getters and setters within your tests right? Check this out..

Calling the cy.task() method to access the getters and setters

Easy peasy! Just call the cy.task() command with the getter or setter name you wrote in the plugins > index.js file.

That’s it! It’s not much of a hassle with Cypress. Try this and let me know of anything you come across, in the comments section below. Clap & Subscribe my Medium account if you are fond of my articles! Stay Safe & Happy Cypressing! ❤

Associate Lead QE @ Nagarro