Discover more from Cypress Testing Tips & Tricks
Use aliases to avoid pyramid of callbacks
Bonus day 31: Avoid pyramid of THEN callbacks by using aliases and a single function callback
Imagine you need to get multiple values from the page before you can check them. For example, you might need to check the order total is the sum of subparts:
We could get each element’s text, convert it to a number, nesting the calls
cy.get('#subtotal')
.invoke('text')
.then(parseFloat)
.then((subtotal) => {
cy.get('#tax')
.invoke('text')
.then(parseFloat)
.then((tax) => {
cy.get('#tip')
.invoke('text')
.then(parseFloat)
.then((tip) => {
// get the total and compare
})
})
})
But there is a better way: save the values using the command cy.as as Cypress aliases. Cypress sets each alias as a property on the test context object, which you can access later if you use function () { … }
callback.
cy.get('#subtotal').invoke('text').then(parseFloat).as('subtotal')
cy.get('#tax').invoke('text').then(parseFloat).as('tax')
cy.get('#tip').invoke('text').then(parseFloat).as('tip')
cy.get('#total')
.invoke('text')
.then(parseFloat)
.as('total')
.then(function () {
expect(this.total, 'total').to.be.closeTo(
this.subtotal + this.tax + this.tip,
0.01,
)
})
The video below shows the above transformation in action.
Tip: Cypress commands are not Promises, thus you cannot use “await” keyword. Instead, the command chains are more like reactive streams, as I spoke about at ReactiveConf conference a while ago, see these slides.
Subscribe to Cypress Testing Tips & Tricks
Tips and tricks about testing all the web things using Cypress.io