Ancora Imparo - I'm still learning (Michelangelo at 87)

How to handle Async code in

In Javascript, there are two major ways through which a code can be executed. They include:

  1. Synchronous JavaScript: The program runs in sequential order; that is, the second line of code can’t be executed until the first line of code has been completed correctly.
  2. Asynchronous JavaScript: All the code runs at the same time. It is unconcerned about the previous code’s state.

It is worthy to note that most API-based or data retrieval events are executed using asynchronous JavaScript. The primary reason is that performing these events take a while, hence instead of the code running in a step-by-step sequence, asynchronous JavaScript is used such that the code returns a “Promise” that it would retrieve data from the API/ database and then execute other lines of code. However, Cypress comes with a “then” method which is used to specify what happens once the data has been retrieved from the API. This is similar to the way JavaScript handles asynchronous code.

An Illustration

Suppose we want to test a piece of asynchronous JavaScript code to retrieve a list of food items from an API, we can perform a test for this using the following lines of code:

describe("asynchronous and promises", () => {
  it("loading the page", () => {
    Cypress.on("uncaught:exception", (err, runnable) => {
      return false;
    cy.visit("").then(() => {
      .select("Rice", "Hamburger", "Pizza", "Hot dog")
      .should("deep.equal", "Pie", "Porridge", "Pasta", "Ice cream")
      .then(() => {});

Once the food data is retrieved from the food API, we can then select a food type like Rice out of the list of foods that are returned as indicated above.

About the Autor

Jamiu Idowu

Jamiu Idowu

Entrepreneur seeking to shape the world through IT and emerging technologies. Enjoys research and technical writing, and can serve as a bridge between technology and its users.

Liked this article?

We have a lot more where that came from!
Join the subscribers who stay ahead of the pack.

By entering your email, you agree to our Terms of Service and Privacy Policy.