Async/Await, Auto-Waiting and Explicit Waits
On this page
Web pages change after they load: a spinner runs, a request comes back, a row appears. Most flaky end-to-end tests are a test that looked for something a moment too early. WebdriverIO handles the common cases for you, as long as you await every command. This chapter shows what it waits for on its own, and the three tools for everything else: waitFor* commands, browser.waitUntil(), and timeouts.
Await everything#
Every WebdriverIO command returns a promise. If you forget await, the command starts but the test moves on before it finishes:
// wrong: the click may not have happened when the next line runs
$('button=Start').click()
await expect($('#finish')).toBeDisplayed()
The next command may run against the page before the click, or the test may end with the click still in flight and report a confusing error in a later test. TypeScript can catch this for you: the @typescript-eslint/no-floating-promises lint rule flags any promise you neither await nor return. It is worth turning on in every WebdriverIO project.
The old synchronous mode, where browser.url() blocked without await, was removed years ago. Tutorials that show test code without await were written for WebdriverIO 6 or earlier.
What WebdriverIO waits for by itself#
When you call a command on an element that is not in the page yet, such as click(), setValue() or getText(), WebdriverIO first waits for the element to exist, for up to waitforTimeout (10 seconds in the course config). It does not wait for the element to become enabled: a check for this course on WebdriverIO 10.2.0, with a button that is enabled two seconds after the page loads, showed click() returning straight away in Chrome and Firefox without an error, and the click had no effect. If an overlay covers the element, the behaviour differs per browser: Chrome retried the click until the overlay was gone, Firefox failed at once with "another element obscures it". So for any state beyond "exists", wait explicitly with waitForEnabled() or waitForClickable() (below) rather than relying on the click. Separately, every expect matcher in expect-webdriverio retries until it passes or its timeout runs out. Those two behaviours cover the first example on the practice site's dynamic loading page, where "Hello World!" is added to the page about five seconds after you click Start:
import { $, $$, browser, expect } from '@wdio/globals'
describe('Waiting', () => {
it('auto-waits for an element that is rendered later', async () => {
await browser.url('/dynamic_loading/2')
await $('button=Start').click()
// #finish is added to the page about five seconds after the click
await expect($('#finish')).toHaveText('Hello World!')
})
})
No sleep, no explicit wait. The matcher keeps looking for #finish and checking its text, and finishes as soon as both are true.
A test clicks "Load more", then calls await browser.pause(3000) before checking that 20 rows exist. It takes three seconds every run and still fails now and then. What is the better version?
The matcher retries until the rows are there and returns as soon as they are. A longer pause is slower and still a guess; reading the length once does not retry at all, so it fails whenever the rows are late.
Waiting for something to go away#
Auto-waiting waits for elements to appear. When you need the opposite, use a waitFor* command. On /dynamic_loading/1, a "Loading..." bar shows while the result is fetched:
it('waits for an element to disappear', async () => {
await browser.url('/dynamic_loading/1')
await $('button=Start').click()
await $('#loading').waitForDisplayed({ reverse: true, timeout: 15000 })
await expect($('#finish')).toBeDisplayed()
})
reverse: true turns "wait until displayed" into "wait until not displayed". The timeout option overrides waitforTimeout for this one call, which is how you give a known-slow operation more time without slowing every other failure in the suite. The family includes waitForExist, waitForDisplayed, waitForClickable and waitForEnabled, all with the same reverse, timeout and timeoutMsg options.
On this page #finish is in the HTML from the start, just hidden, so toBeDisplayed() alone would also work. Waiting for the loader first documents what the test is waiting for, and gives a clearer error ("still displayed after 15000ms") when the backend is slow.
An export takes up to 40 seconds. You raise waitforTimeout to 45000 in wdio.conf.ts. What is the downside?
Passing waits finish early either way, but a missing element now takes 45 seconds to fail everywhere. Give the slow step its own timeout option and keep the global value short.
Waiting for any condition#
Some conditions are not about one element: a count, a value in localStorage, a URL change, a request that finished. browser.waitUntil() polls any async function until it returns a truthy value:
it('waits for a custom condition', async () => {
await browser.url('/add_remove_elements/')
for (let i = 0; i < 3; i++) {
await $('button=Add Element').click()
}
await browser.waitUntil(
async () => (await $$('#elements button').length) === 3,
{ timeout: 5000, timeoutMsg: 'expected three Delete buttons' }
)
})
Always pass a timeoutMsg. Without one, a timeout reports only that a condition was not met, and you have to open the spec to find out which. For this particular check expect($$('#elements button')).toBeElementsArrayOfSize(3) would be shorter; reach for waitUntil when no matcher fits.
What not to do#
-
browser.pause(ms)waits a fixed time whether or not anything happened. It is fine while you watch a test in a debugging session (chapter 9) and wrong in a committed test. -
Implicit waits (
browser.setTimeout({ implicit: 5000 })) make every element lookup wait inside the browser driver. Combined with WebdriverIO's own waiting they multiply delays and hide where a wait is needed. WebdriverIO's defaults do not set one; leave it that way. -
Waiting in page-object getters. A getter that calls
waitForDisplayedruns on every access. Wait in the method that knows why (chapter 5).
The flaky tests course covers timing problems in more depth, including the ones auto-waiting cannot fix, such as animations and data races in the application itself.
Run it#
npx wdio run wdio.conf.ts --spec test/specs/waiting.e2e.ts
[chrome 157.0.8103.78 mac #0-0] Waiting
[chrome 157.0.8103.78 mac #0-0] ✓ auto-waits for an element that is rendered later
[chrome 157.0.8103.78 mac #0-0] ✓ waits for an element to disappear
[chrome 157.0.8103.78 mac #0-0] ✓ waits for a custom condition
[chrome 157.0.8103.78 mac #0-0]
[chrome 157.0.8103.78 mac #0-0] 3 passing (12.4s)
Most of the 12 seconds is the practice site's own deliberate delay on the two loading pages.
A helper does $('#save').click() without await. The test passes locally but fails in CI with an error that points at the next test. What is going on?
A floating promise detaches the command from the test that started it. On a fast machine it happens to finish in time; on a slower runner it does not. Await every command, and let a lint rule enforce it.