A WebdriverIO plugin that provides an adapter for integrating the Mocha testing framework with WebdriverIO's browser automation capabilities.
npx @tessl/cli install tessl/npm-wdio--mocha-framework@9.19.0@wdio/mocha-framework is a WebdriverIO plugin that provides an adapter for integrating the Mocha testing framework with WebdriverIO's browser automation capabilities. It enables developers to write and execute end-to-end browser tests using Mocha's familiar BDD, TDD, and QUnit interfaces with full access to WebdriverIO's browser control APIs.
npm install @wdio/mocha-framework// Main adapter factory
import adapterFactory from "@wdio/mocha-framework";
// Direct class import
import { MochaAdapter } from "@wdio/mocha-framework";
// Common utilities (from /common subpath export)
import { formatMessage, setupEnv, requireExternalModules, loadModule } from "@wdio/mocha-framework/common";
// Type definitions
import type { MochaOpts, FrameworkMessage, FormattedMessage } from "@wdio/mocha-framework";For CommonJS:
const adapterFactory = require("@wdio/mocha-framework");
const { MochaAdapter } = require("@wdio/mocha-framework");// WebdriverIO configuration using the framework
export const config = {
framework: 'mocha',
mochaOpts: {
ui: 'bdd',
timeout: 60000
}
};
// Direct adapter usage (advanced)
import adapterFactory from "@wdio/mocha-framework";
const adapter = await adapterFactory.init(
'session-id',
config,
['/path/to/spec.js'],
{ browserName: 'chrome' },
reporter
);
const exitCode = await adapter.run();The adapter is built around several key components:
Factory function for creating configured MochaAdapter instances.
/**
* Factory object containing the init function for creating MochaAdapter instances
*/
declare const adapterFactory: {
init?: (...args: unknown[]) => Promise<MochaAdapter>;
}
export default adapterFactory;Main adapter class that integrates Mocha with WebdriverIO's test execution flow.
/**
* Main adapter class that integrates Mocha testing framework with WebdriverIO
*/
class MochaAdapter {
/**
* Creates a new MochaAdapter instance
* @param cid - Capability ID for the test session
* @param config - WebdriverIO configuration with Mocha options
* @param specs - Array of test spec file paths
* @param capabilities - Browser capabilities
* @param reporter - Event emitter for test reporting
*/
constructor(
cid: string,
config: ParsedConfiguration,
specs: string[],
capabilities: WebdriverIO.Capabilities,
reporter: EventEmitter
);
/**
* Initializes the adapter and configures Mocha
* @returns Promise resolving to the initialized adapter instance
*/
async init(): Promise<MochaAdapter>;
/**
* Checks whether the adapter has tests to run
* @returns true if tests are available, false otherwise
*/
hasTests(): boolean;
/**
* Runs the test suite and returns the exit code
* @returns Promise resolving to the test run exit code (0 for success)
*/
async run(): Promise<number>;
/**
* Wraps WebdriverIO hooks for async execution within Mocha
* @param hookName - Name of the hook to wrap
* @returns Wrapped hook function
*/
wrapHook(hookName: keyof Services.HookFunctions): () => Promise<void>;
/**
* Prepares framework messages for hooks
* @param hookName - Name of the hook
* @returns Formatted message for the hook
*/
prepareMessage(hookName: keyof Services.HookFunctions): FormattedMessage;
/**
* Emits test events to the reporter
* @param event - Event type
* @param payload - Event payload data
* @param err - Optional error object
*/
emit(event: string, payload: Record<string, unknown>, err?: MochaError): void;
/**
* Generates unique identifiers for test events
* @param message - Framework message to generate UID for
* @returns Unique identifier string
*/
getUID(message: FrameworkMessage): string;
}Utilities for formatting test framework messages for reporting.
/**
* Formats test framework messages for reporting
* @param params - Framework message parameters
* @returns Formatted message object
*/
function formatMessage(params: FrameworkMessage): FormattedMessage;Sets up the testing environment by wrapping global test methods.
/**
* Sets up the testing environment by wrapping global test methods
* @param cid - Capability ID
* @param options - Mocha options
* @param beforeTest - Before test hook
* @param beforeHook - Before hook
* @param afterTest - After test hook
* @param afterHook - After hook
* @returns Array of promises resolving to loaded modules
*/
function setupEnv(
cid: string,
options: MochaOpts,
beforeTest: Hook,
beforeHook: Hook,
afterTest: Hook,
afterHook: Hook
): Promise<unknown>[];Utilities for dynamically loading external modules.
/**
* Requires external modules for compilation/transformation
* @param mods - Array of module names to require
* @param loader - Optional custom loader function
* @returns Array of promises resolving to loaded modules
*/
function requireExternalModules(
mods: string[],
loader?: (name: string) => Promise<unknown>
): Promise<unknown>[];
/**
* Dynamically imports modules with error handling
* @param name - Module name to import
* @returns Promise resolving to the imported module
*/
async function loadModule(name: string): Promise<unknown>;/**
* Mocha configuration options for WebdriverIO
*/
interface MochaOpts {
/** Modules to require before tests */
require?: string[];
/** Compiler modules for file transformation */
compilers?: string[];
/** Allow uncaught errors */
allowUncaught?: boolean;
/** Force done callback or promise */
asyncOnly?: boolean;
/** Bail after first test failure */
bail?: boolean;
/** Check for global variable leaks */
checkLeaks?: boolean;
/** Delay root suite execution */
delay?: boolean;
/** Test filter given string */
fgrep?: string;
/** Tests marked only fail the suite */
forbidOnly?: boolean;
/** Pending tests fail the suite */
forbidPending?: boolean;
/** Full stacktrace upon failure */
fullTrace?: boolean;
/** Variables expected in global scope */
global?: string[];
/** Test filter given regular expression */
grep?: RegExp | string;
/** Invert test filter matches */
invert?: boolean;
/** Number of times to retry failed tests */
retries?: number;
/** Timeout threshold value */
timeout?: number | string;
/** Set test UI to one of the built-in test interfaces */
ui?: 'bdd' | 'tdd' | 'qunit' | 'exports';
}/**
* Error structure for Mocha test failures
*/
interface MochaError {
/** Error name */
name: string;
/** Error message */
message: string;
/** Stack trace */
stack: string;
/** Error type */
type: string;
/** Expected value in assertion */
expected: unknown;
/** Actual value in assertion */
actual: unknown;
}
/**
* Internal message structure for framework events
*/
interface FrameworkMessage {
/** Message type */
type: string;
/** Message payload */
payload?: unknown;
/** Associated error */
err?: MochaError;
}
/**
* Formatted message structure for test reporting
*/
interface FormattedMessage {
/** Message type */
type: string;
/** Capability ID */
cid?: string;
/** Spec file paths */
specs?: string[];
/** Unique identifier */
uid?: string;
/** Test/suite title */
title?: string;
/** Parent suite title */
parent?: string;
/** Full hierarchical title */
fullTitle?: string;
/** Whether test is pending */
pending?: boolean;
/** Whether test passed */
passed?: boolean;
/** Source file path */
file?: string;
/** Execution duration in milliseconds */
duration?: number;
/** Current test name */
currentTest?: string;
/** Test error */
error?: MochaError;
/** Test context */
context?: unknown;
/** Test body */
body?: string;
}/**
* Hook function type used in setupEnv function
*/
type Hook = Function | Function[];The package re-exports Mocha's default export in the types file:
/**
* Default export from Mocha for direct access to Mocha class (from types.ts)
*/
export { default } from 'mocha';declare global {
namespace WebdriverIO {
interface MochaOpts extends MochaOptsImport {}
}
}