Sharing context between tests with Cypress in 3 steps
Today I want to write a short post about how to share context between tests using Cypress — in only 3 steps 🤩. If you've never heard about this tool, according to the official site: "Cypress is a next-generation front end testing tool built for the modern web". It's been heavily used in the frontend because it's a quite clear and simple tool. It uses the Chai assertion library as well as Sinon and jQuery extensions, but the icing on the cake is that Cypress enables us to write end-to-end (E2E), integration, and unit tests. 🤯
Maybe you're wondering "Hey Jenni, we must not share data between tests, they must be independent…🤭". Yeah, that's very true, but sometimes we have some static data that we'll use several times in the same file (.spec). In this post, we'll work with this scenario: sharing information about some personal websites (name and link) and be able to use them whenever we want.
Step 1 — Before hook ☝️
First things first, all tests’ groups are wrapped by a describe
block and inside it, we declare each test using the it
block. There are also hooks that we can use on the tests: before()
, beforeEach()
, after()
and afterEach()
. In our case, we must use the before
hook because it enables us to run a code block before all the tests and it makes sure that the data is accessible in the global context.
Step 2— Aliasing 🗣
Now we have the object pesonalWebsites
that contains the website’s name as key and the site’s link as the value. To make data accessible in Cypress we need to assign it to an alias using cy.as()
.
Under the hood, aliasing basic objects and primitives utilizes Mocha’s shared context object: that is, aliases are available as
this
.
Additionally these aliases and properties are automatically cleaned up after each test.
In the code above, in the line cy.wap(websiteLink).as(websiteName)
we create an alias with the website name as a key and the website link as a value. The command cy.wrap()
just yields something… "cy.as()" doesn’t work without being in a chain.
So when we run the tests, the alias will be available like in the picture below:
Step 3— Tradicional function expression 🌝
Aliases are accessible by using the @aliasName
, but in the shared context scenario we just have access to it using the keyword this
. You must know that arrow functions do not bind their own this
, so we need to use the traditional function expression inside our test blocks.
There you have it! Long story short: we need to alias the data that we want to share on the before hook, replace arrow functions to traditional function expression and access the global context using
this
sweet little thing!
I hope you enjoyed this post! So please, clap around 50 times if it helped you somehow ;) See yah and stay safe! 🤟👩🏻💻