Imagine an application with two input fields and a numerical result element. In the test we need to verify that the result is the sum of the inputs.
1 | <body> |
You can find this page and the spec file in the repo bahmutov/cypress-multiple-aliases.
📺 If you would rather watch the explanation from this blog post, watch it here and subscribe to my YouTube channel.
If we grab each element, then (pun intended) the test will have a pyramid of callback functions.
1 | it('adds numbers', () => { |
Can we avoid this? We could store each parsed number in an alias using .as command.
1 | it('adds numbers via aliases', () => { |
We now need to access all three values at once. If we had just a single value, we could have used cy.get command. For three values, it would lead back to the pyramid of nested callbacks.
1 | it('adds numbers via aliases', () => { |
Instead we can take advantage of the fact that each saved Cypress alias is also added into the test context object. We can access such properties using this.name
later on. To make sure we access the a
, b
, and result
properties after they have been set, we chain the access using .then
1 | it('adds numbers via aliases', () => { |
The test is happy.
Use the function syntax
Note that the callback that accesses the properties from the test context object using this.a
, this.b
, and this.result
is a proper function that uses function () { ... }
syntax. It cannot be () => { ... }
expression, as such expression would not have the this
pointing at the test context object; it would be the global object instead. Thus as a rule of thumb, whenever you use this
inside a Cypress test, always have a proper function
. If you can move your initial code into a beforeEach
hook, then it is trivial:
1 | beforeEach(() => { |
Tip: also check out my library cypress-aliases for simplifying this test even more.
Use valueAsNumber
property
Since we are dealing with number inputs, we can get their numerical values without converting them.
1 | // instead of this |
If you want to print the value to the Command Log, add an assertion
1 | describe('Use beforeEach hook and number values', () => { |
See also
- Read my blog post Tests, closures and arrow functions that has a fine Dante reference.
- 📝 Pass Values Between Cypress Tests