or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

browser.mdcli-config.mdexecution.mdindex.mdinterfaces.mdreporters.md

browser.mddocs/

0

# Browser Support

1

2

Browser-specific functionality for running Mocha tests in web browsers with DOM integration, process shims, and browser-optimized features.

3

4

## Capabilities

5

6

### Browser Setup

7

8

Initialize Mocha for browser environments with configuration and DOM integration.

9

10

```javascript { .api }

11

/**

12

* Browser-specific mocha setup function

13

* @param options - Browser configuration options

14

* @returns {mocha} Global mocha instance

15

*/

16

mocha.setup(options);

17

18

/**

19

* Browser setup options

20

*/

21

interface BrowserSetupOptions {

22

ui?: string; // Interface: 'bdd', 'tdd', 'qunit', 'exports'

23

reporter?: string; // Reporter name (defaults to 'html')

24

timeout?: number; // Global timeout in milliseconds

25

slow?: number; // Slow test threshold

26

grep?: string; // Test filter pattern

27

fgrep?: string; // Fixed string filter

28

invert?: boolean; // Invert grep pattern

29

bail?: boolean; // Bail on first failure

30

checkLeaks?: boolean; // Check for global leaks

31

globals?: string[]; // Global variables to ignore

32

delay?: boolean; // Delay test execution

33

noHighlighting?: boolean; // Disable syntax highlighting

34

}

35

```

36

37

**Usage Examples:**

38

39

```html

40

<!DOCTYPE html>

41

<html>

42

<head>

43

<title>Mocha Tests</title>

44

<link rel="stylesheet" href="node_modules/mocha/mocha.css">

45

</head>

46

<body>

47

<div id="mocha"></div>

48

49

<script src="node_modules/mocha/mocha.js"></script>

50

<script>

51

// Setup Mocha for browser

52

mocha.setup({

53

ui: 'bdd',

54

reporter: 'html',

55

timeout: 5000,

56

slow: 100

57

});

58

</script>

59

60

<!-- Load test files -->

61

<script src="test/browser-tests.js"></script>

62

63

<script>

64

// Run tests when page loads

65

mocha.run();

66

</script>

67

</body>

68

</html>

69

```

70

71

```javascript

72

// String-based setup (shorthand for ui)

73

mocha.setup('bdd');

74

75

// Object-based setup with full options

76

mocha.setup({

77

ui: 'tdd',

78

reporter: 'html',

79

timeout: 10000,

80

globals: ['MY_GLOBAL']

81

});

82

```

83

84

### Browser Test Execution

85

86

Execute tests in browser environment with DOM integration and result display.

87

88

```javascript { .api }

89

/**

90

* Run tests in browser environment

91

* @param callback - Optional completion callback

92

* @returns {Runner} Runner instance

93

*/

94

mocha.run(callback);

95

96

/**

97

* Callback function signature

98

* @param failures - Number of failed tests

99

*/

100

type RunCallback = (failures: number) => void;

101

```

102

103

**Usage Examples:**

104

105

```javascript

106

// Basic execution

107

mocha.run();

108

109

// With completion callback

110

mocha.run(function(failures) {

111

console.log('Tests completed');

112

console.log(`Failed tests: ${failures}`);

113

114

// Report results to parent window or test runner

115

if (window.parent !== window) {

116

window.parent.postMessage({

117

type: 'test-results',

118

failures: failures

119

}, '*');

120

}

121

});

122

123

// Get runner instance for event handling

124

const runner = mocha.run();

125

runner.on('end', function() {

126

console.log('All tests finished');

127

});

128

```

129

130

### Browser Error Handling

131

132

Enhanced error handling for browser environments with assertion integration.

133

134

```javascript { .api }

135

/**

136

* Throw error directly into Mocha's error handling system

137

* Useful for integration with assertion libraries

138

* @param error - Error to throw

139

*/

140

mocha.throwError(error);

141

```

142

143

**Usage Example:**

144

145

```javascript

146

// Integration with assertion libraries

147

function customAssert(condition, message) {

148

if (!condition) {

149

const error = new Error(message);

150

error.name = 'AssertionError';

151

mocha.throwError(error);

152

}

153

}

154

155

// Usage in tests

156

it('should handle custom assertions', function() {

157

customAssert(2 + 2 === 4, 'Math should work');

158

customAssert(true === true, 'Truth should be true');

159

});

160

```

161

162

### Process Shim

163

164

Browser-compatible process object for Node.js compatibility.

165

166

```javascript { .api }

167

/**

168

* Browser process shim - limited process object for compatibility

169

*/

170

interface BrowserProcess {

171

/**

172

* Add event listener for uncaught exceptions

173

* @param event - Event name ('uncaughtException')

174

* @param handler - Error handler function

175

*/

176

on(event: 'uncaughtException', handler: (error: Error) => void): void;

177

178

/**

179

* Remove event listener

180

* @param event - Event name

181

* @param handler - Handler function to remove

182

*/

183

removeListener(event: string, handler: Function): void;

184

185

/**

186

* Get listener count for event

187

* @param event - Event name

188

* @returns {number} Number of listeners

189

*/

190

listenerCount(event: string): number;

191

192

/**

193

* Get all listeners for event

194

* @param event - Event name

195

* @returns {Function[]} Array of listener functions

196

*/

197

listeners(event: string): Function[];

198

199

/**

200

* Standard output stream (browser-stdout shim)

201

*/

202

stdout: any;

203

}

204

205

/**

206

* Access browser process shim

207

*/

208

const process = Mocha.process;

209

```

210

211

### Global Functions Export

212

213

Browser-specific global function exports for ES module compatibility.

214

215

```javascript { .api }

216

/**

217

* Global functions available in browser after setup

218

* These are automatically attached to window/global scope

219

*/

220

221

// BDD interface functions (when ui: 'bdd')

222

function describe(title, fn);

223

function context(title, fn); // alias for describe

224

function it(title, fn);

225

function specify(title, fn); // alias for it

226

227

// Skip functions

228

function xdescribe(title, fn); // skip suite

229

function xcontext(title, fn); // skip suite

230

function xit(title, fn); // skip test

231

function xspecify(title, fn); // skip test

232

233

// Hook functions

234

function before(fn); // before all tests in suite

235

function beforeEach(fn); // before each test

236

function after(fn); // after all tests in suite

237

function afterEach(fn); // after each test

238

239

/**

240

* ES module exports for import usage

241

* Available when using module bundlers

242

*/

243

export {

244

describe, context, it, specify,

245

xdescribe, xcontext, xit, xspecify,

246

before, beforeEach, after, afterEach

247

};

248

```

249

250

### Browser-Specific Features

251

252

Features and optimizations specific to browser environments.

253

254

```javascript { .api }

255

/**

256

* High-performance timer override for browser

257

* Optimized immediate execution scheduling

258

*/

259

Mocha.Runner.immediately = function(callback) {

260

// Browser-optimized immediate execution

261

};

262

263

/**

264

* URL query parameter parsing for browser test configuration

265

* Automatically applied when mocha.run() is called

266

*/

267

interface URLQueryOptions {

268

grep?: string; // Filter tests by pattern

269

fgrep?: string; // Filter tests by fixed string

270

invert?: boolean; // Invert filter pattern

271

}

272

273

// Example URL: test.html?grep=User&invert=true

274

// Automatically applies grep: 'User', invert: true

275

```

276

277

### HTML Reporter Integration

278

279

Browser-specific HTML reporter with DOM integration and syntax highlighting.

280

281

```javascript { .api }

282

/**

283

* HTML reporter automatically integrates with DOM

284

* Requires <div id="mocha"></div> element

285

*/

286

287

/**

288

* HTML reporter features

289

*/

290

interface HTMLReporterFeatures {

291

/**

292

* Automatic syntax highlighting for code blocks

293

* Controlled by noHighlighting option

294

*/

295

syntaxHighlighting: boolean;

296

297

/**

298

* Interactive test result filtering

299

*/

300

interactiveFiltering: boolean;

301

302

/**

303

* Collapsible test suites

304

*/

305

collapsibleSuites: boolean;

306

307

/**

308

* Real-time progress indication

309

*/

310

progressIndicator: boolean;

311

}

312

313

/**

314

* HTML reporter DOM structure

315

*/

316

interface HTMLReporterDOM {

317

container: HTMLElement; // #mocha container

318

stats: HTMLElement; // Test statistics

319

tests: HTMLElement; // Test results

320

progress: HTMLElement; // Progress indicator

321

}

322

```

323

324

### Browser Loading Patterns

325

326

Different approaches for loading Mocha in browsers.

327

328

```javascript { .api }

329

/**

330

* Script tag loading (UMD build)

331

*/

332

// <script src="node_modules/mocha/mocha.js"></script>

333

// Creates global Mocha and mocha objects

334

335

/**

336

* ES module loading (with bundler)

337

*/

338

import { describe, it, before, after } from 'mocha';

339

340

/**

341

* CommonJS loading (with bundler like Browserify)

342

*/

343

const { describe, it } = require('mocha');

344

345

/**

346

* AMD loading (with RequireJS)

347

*/

348

define(['mocha'], function(mocha) {

349

mocha.setup('bdd');

350

return mocha;

351

});

352

```

353

354

### Browser Compatibility

355

356

Browser support and compatibility information.

357

358

```javascript { .api }

359

/**

360

* Supported browsers (as of Mocha 11.7.2)

361

*/

362

interface BrowserSupport {

363

chrome: '>=60'; // Chrome 60+

364

firefox: '>=55'; // Firefox 55+

365

safari: '>=10'; // Safari 10+

366

edge: '>=79'; // Chromium-based Edge

367

ie: false; // Internet Explorer not supported

368

}

369

370

/**

371

* Required browser features

372

*/

373

interface RequiredFeatures {

374

es6: true; // ES6/ES2015 support required

375

promises: true; // Native Promise support

376

eventEmitter: true; // EventEmitter pattern support

377

json: true; // JSON parsing/stringifying

378

setTimeout: true; // Timer functions

379

console: true; // Console logging

380

}

381

```

382

383

### Browser Test Organization

384

385

Best practices and patterns for organizing browser tests.

386

387

```javascript { .api }

388

/**

389

* Recommended browser test structure

390

*/

391

392

// test/browser/setup.js

393

mocha.setup({

394

ui: 'bdd',

395

reporter: 'html',

396

timeout: 5000

397

});

398

399

// test/browser/utils.js

400

function waitForElement(selector) {

401

return new Promise(resolve => {

402

const check = () => {

403

const el = document.querySelector(selector);

404

if (el) resolve(el);

405

else setTimeout(check, 10);

406

};

407

check();

408

});

409

}

410

411

// test/browser/dom-tests.js

412

describe('DOM Tests', function() {

413

beforeEach(function() {

414

document.body.innerHTML = '<div id="app"></div>';

415

});

416

417

afterEach(function() {

418

document.body.innerHTML = '';

419

});

420

421

it('should create DOM elements', async function() {

422

const app = document.getElementById('app');

423

app.innerHTML = '<button>Click me</button>';

424

425

const button = await waitForElement('button');

426

assert(button.textContent === 'Click me');

427

});

428

});

429

430

// test/browser/run.js

431

mocha.run(function(failures) {

432

console.log(`Browser tests completed: ${failures} failures`);

433

});

434

```