Skip to main content

the-use-of-cypress-then-method

This article primarily discusses the usage of the .then() method in Cypress and Cypress's testing strategy.

––– views

then | Cypress

Introduction

In Cypress, the .then() method is a crucial tool that allows us to access the result of a previous command. Its primary uses include accessing values of DOM elements, objects, or arrays related to your test, or making assertions based on the result of previous actions.

test.cy.ts

_10
cy.get('.my-selector').then(($elements) => {
_10
// Here, you have access to all '.my-selector' elements
_10
})

Wait test

However, Cypress operates asynchronously; by design, it automatically waits for assertions to pass or timeouts to occur. This behavior is extremely useful when dealing with dynamic web pages and asynchronous operations, eliminating the recurring problem of flaky and fragile tests induced by timing issues. No more hard-coded waits or timeouts in your test code.

test.cy.ts

_10
cy.get('.some-selector').then(($elements) => {
_10
cy.wrap($elements.length).should('be.gte', 5) // Cypress will wait for the length to be greater than or equal to 5
_10
})

It's crucial to note that while this behavior of Cypress is sufficient for most scenarios, and indeed, its capacity to handle asynchronous operations without explicit waits is a unique strength, Cypress might not suit your needs if you want your code to fail and stop execution immediately under certain circumstances. It may be necessary to seek other tools or try alternative testing strategies.

No Wait test

The script is an example of a no-wait approach in Cypress, where explicit waiting is not required, taking full advantage of Cypress's asynchronous nature and automatic retryability. Rather than manually adding waits or timeouts, this test relies on Cypress's built-in mechanisms to handle asynchronicity and ensure the test's reliability.

test.cy.ts

_10
let tempLength: number
_10
const initialLength = 0
_10
_10
cy.get('.some-selector')
_10
.its('length')
_10
.then((length) => {
_10
tempLength = length
_10
return tempLength
_10
})
_10
.should('be.gt', initialLength)