How to handle Cypress Asynchronous Behavior?

On This Page What is Cypress Asynchronous Behavior?April 11, 2026 · 10 min read · Tool Comparison

How to treat Cypress Asynchronous Behavior?

Cypress bid are asynchronousand queued for later performance, which can cause disarray.

Since command run consecutive, exam may look to malfunction if one command is waiting for another to complete. Understanding and managing this behavior is crucial for smooth and accurate test execution.

This article explains how to handle Cypress & # 8217; s asynchronous nature and avoid common issues.

What is Cypress Asynchronous Behavior?

Asynchronous Behaviorrefers to how commands are executed consecutive but handled asynchronously without waiting for the previous command to complete. Though the code is pen sequentially, each bid in Cypress is queued and runs independently, allowing tests to move without waiting for earlier commands to dispatch.

Asynchronous conduct executes steps concurrently without wait for the old one to finish, improving efficiency but requiring careful cover to avoid errors from incomplete commands.

Also Read:

The difference between synchronous and asynchronous executing in Cypress is like to how client-server Call are handled, where one doesn ’ t depend on the completion of the other.

The difference between both is illustrated below.

Every Cypress dictation has an asynchronous nature. Cypress has a wrapper that reads the sequential code we write, enqueues it, and executes it later. So, Cypress fulfills all our tasks touch to promise and async nature.

Example:

The instance of asynchronous conduct in Cypress is provided below to help you comprehend the mind.

describe ('Cypress ', role () {it ('Example 1 ', function () {// launching Url URL cy.visit (`` https: //example.cypress.io/ '') // identifying element cy.get ('h1 ') .should ('have.text ', 'Kitchen Sink ') cy.get ('h1 ') .then (use (e) {const t = e.text () // get in Console console.log (t)}) // Console message console.log (`` Cypress Tutorial '')})})

The result is provided below:

Promises to handle Cypress Asynchronous Behavior

Before beginning to fulfil any commands, Cypress puts them all in a queue. Programming words promises are quite like to general language hope made to humankind. A promise is a condition that represents a mortal & # 8217; s behavior or action.

Depending on the consideration and nature, a person can either keep or interrupt the Promise. When the Promise conduct place, it is in an irrational state that might either resolve to be fulfilled or become refused.

On the like note, Promise is a state of the command in the case of Cypress async tests, and it will hold the following province:

  • Resolved:If the test phase is successful.
  • Pending:If the exam form run result is being expect.
  • Rejected:If the test stage is stillborn.

A Cypress command fulfill only when the previous step has been executed successfully, or a single-minded promise response has been find. Then, Promise is added to Cypress using the method.

Example of a Promise in Cypress:

describe ('Cypress Test ', function () {it ('Promise ', function () {return cy.visit ('https: //example.cypress.io/ ') .then (() = & gt; {regress cy.get ('h1 ');})})})

The codification in the example above is clear and simple to read and comprehend. All promise-related employment is handled in, which keeps it from the user & # 8217; s panorama. Thus, we won & # 8217; t need to be concerned about handling or returning the promise.

Advanced Techniques for Handling Asynchronous Behavior

To avoid, it is essential to have a solid testing strategy for dealing with asynchronous activities. We & # 8217; ll go through a few for handling this in your Cypress async tests down below.

cy.wait

Before action the next command, await a predetermined number of milliseconds or until an aliased resource has resolved.

Syntax:

cy.wait (time) cy.wait (alias) cy.wait (alias) cy.wait (time, pick) cy.wait (alias, options) cy.wait (aliases, options)

Arguments:

  • clip (Number):The number of msec to await.
  • alias (String):An aliased path that has been defined using the .as () command and is identified by the @ sign and the alias & # 8217; s name.
  • aliases (Array): An array of aliased routes that have been defined with the .as () command and are place by the @ signaling and the alias name.
  • options (Object): Use an alternative object to override cy.wait () default operation
OptionDefaultDescription
logtrueMakes the bidding visible in the Command log.
timeoutrequestTimeout, responseTimeoutDuration of the wait for cy.wait () to settle before timing out
requestTimeoutrequestTimeoutChanges the request & # 8217; s global requestTimeout.
responseTimeoutresponseTimeoutChanges the request & # 8217; s world requestTimeout.

async/await

Cypress manages asynchronous behavior through its command queue, but when working with external asynchronous code like API ring or custom JavaScript functions—async/await aid control the flow.

Syntax:

javascript async office functionName () {const answer = await asyncOperation (); // Code that bunk after the async operation completes}

Example:

javascript async function fetchData () {const response = await fetch ('https: //api.example.com/data '); return response.json ();} it ('handles international async logic ', async () = & gt; {const data = await fetchData (); expect (data) .to.have.property ('id '); cy.visit ('/dashboard '); cy.get ('.item ') .should ('contain ', data.name);});

Here, await fetchData ()pauses executing until the API reply is get before Cypress commands continue.

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

When to Use cy.wait () vs. async/await

  • Use cy.wait()for Cypress-native asynchronous conduct, such as waiting for API responses, DOM update, or user interaction.
  • Use async/awaitwhen handling international promise or custom asynchronous functions outside of Cypress ’ s control.

How cy.wait () differs from await:

  • Scope of Use: cy.wait ()is specific to Cypress bid (e.g., waiting for network request or DOM changes), while await handles generic JavaScript hope external Cypress.
  • Command Queue Integration: cy.wait ()is part of Cypress ’ s built-in bidding chain and automatically handles retries. In demarcation, await works outside the Cypress chain and doesn ’ t have retry logic.
  • Control Flow: cy.wait ()doesn ’ t interruption JavaScript executing; it wait within Cypress ’ s bidding flow.awaitpauses the entire function ’ s execution until the hope resolves.

cy.tick

After supplant a native time function with cy.clock (), move time. To override aboriginal time functions first, cy.clock () must be called before cy.tick ().

Syntax:

cy.tick (milliseconds, options)

Arguments:

  • msec (Number):The number of milliseconds needed to move the clock. All timer that descend within the wedged period will be called.
  • options (Object):To modify cy.tick () default behavior, furnish an options object.
OptionDefaultDescription
logtrueMakes the command visible in the Command log.

.then()

A bid may occasionally render a subject rather than return it. In that situation, we use .then () to communicate with the subject directly.

Promises and .then () act identically. However, unlike a Promise, .then () is a Cypress command. As a result, we can not use async/await in the test script.

The recall function & # 8217; s yield becomes the new subject and feeds the command that follows (except for undefined).

cy.get (`` button '') .then (($ btn) = & gt; {const cls = $ btn.attr (`` form '') // ...})

.wrap()

In the above example, $ btn is a jQuery object. This implies that for Cypress to interact with it and conduct some action, we must foremost use cy.wrap ().

cy.get (`` button '') .then (($ btn) = & gt; {const cls = $ btn.attr (`` family '') cy.wrap ($ btn) .click () .should (`` not.have.class '', cls)})

In this example, the & lt; button & gt; HTML component comes first. Our subject, in this illustration, is the HTML ingredient designated as & lt; button & gt;, which is yielded from cy.get () to .then (). To execute any operation or assertions on the study, we must firstly .wrap () it. The subject can so be accessed as the varying $ btn.

Cypress must .click () the button before making our asseveration, which in this representative is .should (& # 8216; not.have.class & # 8217;, cls). We must first enfold our $ btn with cy.wrap () in order to give Cypress the right context to click on it.

Debugging Cypress Asynchronous Behavior

The ability to fleetly name the source movement of errors and bugs whenever you come across them, is one of a software tester & # 8217; s most crucial skills. This proceed beyond simply write code chop-chop. Hence Debugging is crucial in automated scheduling because of this.

We & # 8217; ll discourse a few of the most effective techniques for debugging our Cypress async test and go into outstanding particular on each.

1. Using a Debugger

It can often be really challenging to place precisely what went incorrect and which share of the codification miscarry to perform as intended while scat exam, especially turgid and complex ones. In example like this, the debugger is highly beneficial.

Although utilizing the debugger in Cypress is very like to doing so in former region of your program (such as the front end), it doesn & # 8217; t operate similarly.

  • In Cypress, the .then () function is the only place where the debugger can be expend. If not, the debugger will stop the test from running before it e'er begins.
  • The debugger will debar test execution after the .then () method ensures that the Cypress command runs and completes.
it ('should pause only when the cy.get () execute ', () = & gt; {cy.visit ('https: //example.cypress.io/ ') cy.get ('h1 ') .should ('exist ') .then ($ h1 = & gt; {debugger})})

In this section of, the debugger will exclusively break the test if the h1 element exists in the DOM since we are saying that the debugger should entirely pause the trial only if the h1 element exist in the DOM.

The issue is provided below:

As you can see, the debugger now only pauses the test once it has located the factor and verified that it is present in the DOM; differently, it will raise an error.

2. Using the .debug ()

You can chain the Cypress debugging shortcut, .debug (), to any other Cypress command across your tests. When it is called, the .debug () function will uncover sure information in the browser & # 8217; s console.

  • Command Name:The name of the most recent bid run before the .debug () use was called.
  • Command Args:The list of disceptation passed to the last method before calling .debug ().
  • Current Subject:A new variable with the name subject will be yield inside the browser. You can use the console to interact with it. The subject variable, the Cypress command & # 8217; s return value, can be interacted with using the browser console.

We & # 8217; ll get the first H1 factor on the page for this example.

it ('should pause the tryout by using the .debug () command ', () = & gt; {cy.visit ('https: //example.cypress.io/ ') cy.get ('h1 ') .should ('exist ') .debug () // debugger})

The result is provided below:

  • We can interact with the current subject that is returned by cy.get () in the console by using the exposed variable content in our developer instrument.
  • During the test, We can easily check any or many areas of our application by using the .debug () function. To view the system & # 8217; s current state, we can tie it to any Cypress set of bid.

3. Using the Developer Tools

Another method for debug our code and understanding what come when running tests is using the console logs render by Developer Tool.

  • The cy.log () command and the standard JavaScript console.log () function are the two commands, we can use to log outputs into the console of our browser.
  • To console.log (), we should do any Cypress command & # 8217; s regress value inside the .then () method.
  • The proper method for lumber the return value of any Cypress command is to do so inside of .then () function. In this manner, after we log it, we will receive the actual element.

This is the proper trend of action.

it ('should return the actual h1 element ', () = & gt; {cy.visit ('https: //example.cypress.io/ ') cy.get ('h1 ') .then ($ h1 = & gt; {// this will log the literal value of the `` h1 '' element console.log ($ h1)})})

The result is provided below:

Must-Read:

Using BrowserStack for Cypress Test Automation

Here ’ s why BrowserStack is idealistic for Cypress test mechanisation:

  • : Cypress support mainly Chrome-based browsers, but BrowserStack extends compatibility to Safari, Edge, IE, and more.
  • Cloud Infrastructure: No need to set up or maintain local browsers or devices, BrowserStack provides a cloud-based answer.
  • : Run multiple tests simultaneously to speed up performance and shorten release cycles.
  • : Test on 3,500+ existent device-browser-OS combinations, ensuring accurate solution under.
  • : Easily integrates with alike Jenkins, CircleCI, and Bamboo.
  • Scalability: Run hundreds of tests across various environment with real-device and parallel quiz on cloud infrastructure.

Talk to an Expert

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Conclusion

This article has analyse asynchronously loading browser constituent as well as the linkage between Cypress and asynchronous loading. When, we discussed various access to dealing with asynchronous codification. We examined Cypress & # 8217; interior handling of promises, which permit us to create clearer and more comprehensible examination. Also, we looked at methods for debugging Cypress programs.

It is easier to integrate the with Browserstack, which will give squad a clearer understanding of the test outcomes. Understand that Cypress testing must be action on existent browsers for accurate answer. Start testing on 30+ versions of the late browsers across Windows and macOS with BrowserStack.

Tags
59,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free