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.00
# @wdio/mocha-framework
1
2
@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.
3
4
## Package Information
5
6
- **Package Name**: @wdio/mocha-framework
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @wdio/mocha-framework`
10
11
## Core Imports
12
13
```typescript
14
// Main adapter factory
15
import adapterFactory from "@wdio/mocha-framework";
16
17
// Direct class import
18
import { MochaAdapter } from "@wdio/mocha-framework";
19
20
// Common utilities (from /common subpath export)
21
import { formatMessage, setupEnv, requireExternalModules, loadModule } from "@wdio/mocha-framework/common";
22
23
// Type definitions
24
import type { MochaOpts, FrameworkMessage, FormattedMessage } from "@wdio/mocha-framework";
25
```
26
27
For CommonJS:
28
29
```javascript
30
const adapterFactory = require("@wdio/mocha-framework");
31
const { MochaAdapter } = require("@wdio/mocha-framework");
32
```
33
34
## Basic Usage
35
36
```typescript
37
// WebdriverIO configuration using the framework
38
export const config = {
39
framework: 'mocha',
40
mochaOpts: {
41
ui: 'bdd',
42
timeout: 60000
43
}
44
};
45
46
// Direct adapter usage (advanced)
47
import adapterFactory from "@wdio/mocha-framework";
48
49
const adapter = await adapterFactory.init(
50
'session-id',
51
config,
52
['/path/to/spec.js'],
53
{ browserName: 'chrome' },
54
reporter
55
);
56
57
const exitCode = await adapter.run();
58
```
59
60
## Architecture
61
62
The adapter is built around several key components:
63
64
- **Adapter Factory**: Entry point that creates and initializes MochaAdapter instances
65
- **MochaAdapter Class**: Core adapter that manages Mocha integration with WebdriverIO
66
- **Event System**: Maps Mocha events to WebdriverIO events for reporting and lifecycle management
67
- **Hook Integration**: Wraps WebdriverIO hooks to work within Mocha's execution flow
68
- **Message Formatting**: Transforms internal framework messages into structured reporting data
69
70
## Capabilities
71
72
### Adapter Factory
73
74
Factory function for creating configured MochaAdapter instances.
75
76
```typescript { .api }
77
/**
78
* Factory object containing the init function for creating MochaAdapter instances
79
*/
80
declare const adapterFactory: {
81
init?: (...args: unknown[]) => Promise<MochaAdapter>;
82
}
83
84
export default adapterFactory;
85
```
86
87
### MochaAdapter Class
88
89
Main adapter class that integrates Mocha with WebdriverIO's test execution flow.
90
91
```typescript { .api }
92
/**
93
* Main adapter class that integrates Mocha testing framework with WebdriverIO
94
*/
95
class MochaAdapter {
96
/**
97
* Creates a new MochaAdapter instance
98
* @param cid - Capability ID for the test session
99
* @param config - WebdriverIO configuration with Mocha options
100
* @param specs - Array of test spec file paths
101
* @param capabilities - Browser capabilities
102
* @param reporter - Event emitter for test reporting
103
*/
104
constructor(
105
cid: string,
106
config: ParsedConfiguration,
107
specs: string[],
108
capabilities: WebdriverIO.Capabilities,
109
reporter: EventEmitter
110
);
111
112
/**
113
* Initializes the adapter and configures Mocha
114
* @returns Promise resolving to the initialized adapter instance
115
*/
116
async init(): Promise<MochaAdapter>;
117
118
/**
119
* Checks whether the adapter has tests to run
120
* @returns true if tests are available, false otherwise
121
*/
122
hasTests(): boolean;
123
124
/**
125
* Runs the test suite and returns the exit code
126
* @returns Promise resolving to the test run exit code (0 for success)
127
*/
128
async run(): Promise<number>;
129
130
/**
131
* Wraps WebdriverIO hooks for async execution within Mocha
132
* @param hookName - Name of the hook to wrap
133
* @returns Wrapped hook function
134
*/
135
wrapHook(hookName: keyof Services.HookFunctions): () => Promise<void>;
136
137
/**
138
* Prepares framework messages for hooks
139
* @param hookName - Name of the hook
140
* @returns Formatted message for the hook
141
*/
142
prepareMessage(hookName: keyof Services.HookFunctions): FormattedMessage;
143
144
/**
145
* Emits test events to the reporter
146
* @param event - Event type
147
* @param payload - Event payload data
148
* @param err - Optional error object
149
*/
150
emit(event: string, payload: Record<string, unknown>, err?: MochaError): void;
151
152
/**
153
* Generates unique identifiers for test events
154
* @param message - Framework message to generate UID for
155
* @returns Unique identifier string
156
*/
157
getUID(message: FrameworkMessage): string;
158
}
159
```
160
161
### Message Formatting
162
163
Utilities for formatting test framework messages for reporting.
164
165
```typescript { .api }
166
/**
167
* Formats test framework messages for reporting
168
* @param params - Framework message parameters
169
* @returns Formatted message object
170
*/
171
function formatMessage(params: FrameworkMessage): FormattedMessage;
172
```
173
174
### Environment Setup
175
176
Sets up the testing environment by wrapping global test methods.
177
178
```typescript { .api }
179
/**
180
* Sets up the testing environment by wrapping global test methods
181
* @param cid - Capability ID
182
* @param options - Mocha options
183
* @param beforeTest - Before test hook
184
* @param beforeHook - Before hook
185
* @param afterTest - After test hook
186
* @param afterHook - After hook
187
* @returns Array of promises resolving to loaded modules
188
*/
189
function setupEnv(
190
cid: string,
191
options: MochaOpts,
192
beforeTest: Hook,
193
beforeHook: Hook,
194
afterTest: Hook,
195
afterHook: Hook
196
): Promise<unknown>[];
197
```
198
199
### Module Loading
200
201
Utilities for dynamically loading external modules.
202
203
```typescript { .api }
204
/**
205
* Requires external modules for compilation/transformation
206
* @param mods - Array of module names to require
207
* @param loader - Optional custom loader function
208
* @returns Array of promises resolving to loaded modules
209
*/
210
function requireExternalModules(
211
mods: string[],
212
loader?: (name: string) => Promise<unknown>
213
): Promise<unknown>[];
214
215
/**
216
* Dynamically imports modules with error handling
217
* @param name - Module name to import
218
* @returns Promise resolving to the imported module
219
*/
220
async function loadModule(name: string): Promise<unknown>;
221
```
222
223
## Types
224
225
### Configuration Types
226
227
```typescript { .api }
228
/**
229
* Mocha configuration options for WebdriverIO
230
*/
231
interface MochaOpts {
232
/** Modules to require before tests */
233
require?: string[];
234
/** Compiler modules for file transformation */
235
compilers?: string[];
236
/** Allow uncaught errors */
237
allowUncaught?: boolean;
238
/** Force done callback or promise */
239
asyncOnly?: boolean;
240
/** Bail after first test failure */
241
bail?: boolean;
242
/** Check for global variable leaks */
243
checkLeaks?: boolean;
244
/** Delay root suite execution */
245
delay?: boolean;
246
/** Test filter given string */
247
fgrep?: string;
248
/** Tests marked only fail the suite */
249
forbidOnly?: boolean;
250
/** Pending tests fail the suite */
251
forbidPending?: boolean;
252
/** Full stacktrace upon failure */
253
fullTrace?: boolean;
254
/** Variables expected in global scope */
255
global?: string[];
256
/** Test filter given regular expression */
257
grep?: RegExp | string;
258
/** Invert test filter matches */
259
invert?: boolean;
260
/** Number of times to retry failed tests */
261
retries?: number;
262
/** Timeout threshold value */
263
timeout?: number | string;
264
/** Set test UI to one of the built-in test interfaces */
265
ui?: 'bdd' | 'tdd' | 'qunit' | 'exports';
266
}
267
268
```
269
270
### Message Types
271
272
```typescript { .api }
273
/**
274
* Error structure for Mocha test failures
275
*/
276
interface MochaError {
277
/** Error name */
278
name: string;
279
/** Error message */
280
message: string;
281
/** Stack trace */
282
stack: string;
283
/** Error type */
284
type: string;
285
/** Expected value in assertion */
286
expected: unknown;
287
/** Actual value in assertion */
288
actual: unknown;
289
}
290
291
/**
292
* Internal message structure for framework events
293
*/
294
interface FrameworkMessage {
295
/** Message type */
296
type: string;
297
/** Message payload */
298
payload?: unknown;
299
/** Associated error */
300
err?: MochaError;
301
}
302
303
/**
304
* Formatted message structure for test reporting
305
*/
306
interface FormattedMessage {
307
/** Message type */
308
type: string;
309
/** Capability ID */
310
cid?: string;
311
/** Spec file paths */
312
specs?: string[];
313
/** Unique identifier */
314
uid?: string;
315
/** Test/suite title */
316
title?: string;
317
/** Parent suite title */
318
parent?: string;
319
/** Full hierarchical title */
320
fullTitle?: string;
321
/** Whether test is pending */
322
pending?: boolean;
323
/** Whether test passed */
324
passed?: boolean;
325
/** Source file path */
326
file?: string;
327
/** Execution duration in milliseconds */
328
duration?: number;
329
/** Current test name */
330
currentTest?: string;
331
/** Test error */
332
error?: MochaError;
333
/** Test context */
334
context?: unknown;
335
/** Test body */
336
body?: string;
337
}
338
```
339
340
### Utility Types
341
342
```typescript { .api }
343
/**
344
* Hook function type used in setupEnv function
345
*/
346
type Hook = Function | Function[];
347
```
348
349
### Re-exports
350
351
The package re-exports Mocha's default export in the types file:
352
353
```typescript { .api }
354
/**
355
* Default export from Mocha for direct access to Mocha class (from types.ts)
356
*/
357
export { default } from 'mocha';
358
```
359
360
361
## Global Type Extensions
362
363
```typescript { .api }
364
declare global {
365
namespace WebdriverIO {
366
interface MochaOpts extends MochaOptsImport {}
367
}
368
}
369
```