Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Webdriverio Webdriverio Mocha BDD Globals

From Leeroopedia

Overview

Wrapper documentation for Mocha BDD test syntax with WebdriverIO-injected globals for browser automation testing.

Metadata

Field Value
Page Type Implementation (Wrapper Doc)
Repository webdriverio/webdriverio
Packages @wdio/mocha-framework, @wdio/globals
External Reference Mocha BDD Interface, WDIO Globals API
Related Principle Principle: Test_Spec_Authoring

Description

When using the WDIO testrunner with framework: 'mocha', the MochaAdapter sets up Mocha's BDD interface (describe, it, before, after, beforeEach, afterEach) and the @wdio/globals module injects browser, $, $$, and expect into the test worker scope. Tests use describe/it for structure and the globals for browser interaction without explicit imports.

The MochaAdapter wraps the standard Mocha test runner with WDIO-specific lifecycle management: it maps Mocha events to WDIO reporter events, wraps hook execution with executeHooksWithArgs for proper error handling, and provides UID-based tracking for nested suite/test hierarchies.

The globals module uses a Proxy-based delegation pattern. Each exported global (browser, $, $$, expect) is a Proxy that intercepts property access and delegates to the real object stored in a global Map (globalThis._wdioGlobals). This enables the globals to work across both ESM and CJS module boundaries within the same worker process.

Source References

File Lines Description
packages/wdio-mocha-framework/src/index.ts L30-288 MochaAdapter class: initializes Mocha, loads specs, runs tests, emits events
packages/wdio-mocha-framework/src/common.ts L151-176 setupEnv(): configures BDD/TDD/QUnit interface and wraps global test methods
packages/wdio-mocha-framework/src/constants.ts L1-30 INTERFACES, TEST_INTERFACES, EVENTS mapping (Mocha events to WDIO events)
packages/wdio-globals/src/index.ts L1-134 Proxy-based globals: browser, driver, $, $$, expect, _setGlobal()

APIs

Mocha BDD Interface (injected globally)

Function Signature Description
describe describe(title: string, fn: () => void): void Define a test suite
it it(title: string, fn: () => Promise<void>): void Define an individual test case
before before(fn: () => Promise<void>): void Run once before all tests in a suite
beforeEach beforeEach(fn: () => Promise<void>): void Run before each test in a suite
after after(fn: () => Promise<void>): void Run once after all tests in a suite
afterEach afterEach(fn: () => Promise<void>): void Run after each test in a suite

WDIO Globals (injected by testrunner)

Global Type Description
browser WebdriverIO.Browser (Proxy) The automated browser session; provides url(), getTitle(), execute(), etc.
$ (selector: string) => WebdriverIO.Element Shorthand for browser.$(selector); returns a single element
$$ (selector: string) => WebdriverIO.Element[] Shorthand for browser.$$(selector); returns multiple elements
expect ExpectWebdriverIO.Expect Assertion function with WDIO-specific matchers (toBeDisplayed, toHaveText, etc.)
driver WebdriverIO.Browser (Proxy) Alias for browser

Import

No import is needed -- globals are injected by the testrunner automatically. If explicit imports are desired (e.g., for IDE autocompletion outside the testrunner):

import { browser, $, $$, expect } from '@wdio/globals'

Mocha Event Mapping

The MochaAdapter maps Mocha runner events to WDIO reporter events:

Mocha Event WDIO Event
suite suite:start
suite end suite:end
test test:start
test end test:end
hook hook:start
hook end hook:end
pass test:pass
fail test:fail
retry test:retry
pending test:pending

Supported UI Types

The MochaAdapter supports multiple Mocha interfaces, configured via mochaOpts.ui:

UI Type Test Functions Hook Functions
bdd (default) it, specify before, beforeEach, after, afterEach
tdd test suiteSetup, setup, suiteTeardown, teardown
qunit test before, beforeEach, after, afterEach

Usage Example

// test/specs/login.spec.ts
// No imports needed -- describe, it, browser, $, $$, expect are all globals

describe('Login Page', () => {
    before(async () => {
        // Runs once before all tests in this describe block
        await browser.url('/login')
    })

    it('should display the login form', async () => {
        const form = await $('#login-form')
        await expect(form).toBeDisplayed()
    })

    it('should accept valid credentials', async () => {
        await $('#username').setValue('testuser')
        await $('#password').setValue('secret')
        await $('button[type="submit"]').click()

        // WDIO-specific assertion matcher
        await expect(browser).toHaveUrl(expect.stringContaining('/dashboard'))
    })

    it('should show all navigation links', async () => {
        const links = await $$('nav a')
        await expect(links).toBeElementsArrayOfSize({ gte: 3 })
    })
})

Configuration for Mocha framework

// wdio.conf.ts
export const config: WebdriverIO.Config = {
    framework: 'mocha',
    mochaOpts: {
        ui: 'bdd',           // default
        timeout: 60000,      // test timeout in ms
        retries: 1,          // retry failed tests once
        grep: 'login',       // only run tests matching pattern
        invert: false
    },
    // ...
}

Globals Proxy Mechanism

The @wdio/globals package uses a Proxy handler to lazily delegate access:

// packages/wdio-globals/src/index.ts L27-42
function proxyHandler(key: SupportedGlobals) {
    return {
        get: (self: never, prop: any) => {
            if (!globals.has(key)) {
                throw new Error(
                    'No browser instance registered. Don\'t import @wdio/globals ' +
                    'outside of the WDIO testrunner context.'
                )
            }
            const receiver = globals.get(key)
            const field = receiver[prop]
            return typeof field === 'function'
                ? field.bind(receiver)
                : field
        }
    }
}

export const browser: WebdriverIO.Browser = new Proxy(
    class Browser {} as unknown as WebdriverIO.Browser,
    proxyHandler('browser')
)

The testrunner registers actual implementations via the private _setGlobal(key, value) function, which stores the value in the shared Map and optionally sets it on globalThis.

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment