How to use promise in Cypress with Javascript

A Promise is used to handle the result of an asynchronous operation. It represents a value that may be available now, in the future, or never. A Promise can be in one of three states:

  • Pending – the operation is still in progress
  • Resolved (Fulfilled) – the operation completed successfully
  • Rejected – the operation failed

Promises are commonly used in JavaScript to manage asynchronous behavior.

In Cypress, JavaScript operations are asynchronous by nature. Cypress commands themselves are already promise-like and automatically handle waiting and retries. However, native JavaScript Promises can still be used when working with non-Cypress asynchronous code (such as custom utilities, APIs, or third-party libraries). In such cases, Promises can be integrated with Cypress using cy.wrap() or by returning the Promise, which helps keep the test execution smooth and predictable.

An example of a JavaScript Promise is shown below:

Example: JavaScript Promise

function getUserData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;

  if (success) {
    resolve("User data loaded successfully");
  } else {
    reject("Failed to load user data");
  }
}, 2000);

});
}

Using the Promise in Cypress

Cypress does not allow direct use of .then() on native Promises unless they are wrapped. Use cy.wrap() to integrate the Promise into the Cypress command chain.

Example Cypress Script:

it(‘uses a Promise in Cypress’, () => {
cy.wrap(getUserData()).then((message) => {
cy.log(message);
expect(message).to.equal(“User data loaded successfully”);
});
});

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x