Cypress .then is not a promise!

Giacomo Voß
2 min readMar 13, 2023

--

Photo by alise storsul on Unsplash

If you’re a Cypress user, you’re probably familiar with the “then” keyword. It’s commonly used to access and manipulate the results of a Cypress command. However, many developers mistakenly assume that the “then” keyword is related to Promises, as it’s a common method for handling Promise chains in JavaScript. In reality, the “then” keyword in Cypress has nothing to do with Promises.

To understand why the “then” keyword in Cypress is not related to Promises, let’s take a closer look at how it works. In Cypress, each command returns a Chainable object, which is a wrapper around a jQuery element. The “then” keyword is used to access the result of a command and perform additional actions on it.

For example, let’s say we want to get the text of a button and log it to the console:

cy.get('button').invoke('text').then((text) => {
console.log(text)
})

In this example, the get command returns a Chainable object that represents the button element. The invoke command is used to get the text of the button. Finally, the "then" keyword is used to log the text to the console.

Note that the “then” keyword is not used to handle a Promise chain. Instead, it’s used to access the result of a command and perform additional actions on it. This is because Cypress commands are not Promises. They are actually wrapped in a special type of object that allows Cypress to control the order in which they are executed.

This is an important distinction, as assuming that Cypress commands are Promises can lead to confusion and errors. For example, if you try to use a Promise method like “catch” on a Cypress command, it will not work as expected:

cy.get('button').catch((error) => {
console.log(error)
})

In this example, the “catch” method will not be called, as it’s not a valid method on a Cypress command.

In conclusion, the “then” keyword in Cypress has nothing to do with Promises. It’s simply a way to access the result of a command and perform additional actions on it. While it may look similar to Promise syntax, it’s important to understand the differences between Cypress commands and Promises to avoid confusion and errors in your tests.

--

--