or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-karma-mocha

A Karma plugin adapter for the Mocha testing framework enabling browser-based test execution

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/karma-mocha@2.0.x

To install, run

npx @tessl/cli install tessl/npm-karma-mocha@2.0.0

0

# karma-mocha

1

2

karma-mocha is a Karma plugin that serves as an adapter for the Mocha testing framework. It enables developers to run Mocha tests within the Karma test runner environment, providing seamless integration between Karma's browser-based test execution platform and Mocha's behavior-driven development testing capabilities.

3

4

## Package Information

5

6

- **Package Name**: karma-mocha

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install karma-mocha mocha --save-dev`

10

11

## Core Imports

12

13

The package registers itself as a Karma framework plugin - no direct imports needed in test files:

14

15

```javascript

16

// karma.conf.js

17

module.exports = function(config) {

18

config.set({

19

frameworks: ['mocha'], // karma-mocha registers the 'mocha' framework

20

files: ['test/**/*.js']

21

});

22

};

23

```

24

25

## Basic Usage

26

27

```javascript

28

// karma.conf.js - Basic configuration

29

module.exports = function(config) {

30

config.set({

31

frameworks: ['mocha'],

32

files: ['test/**/*.spec.js'],

33

browsers: ['Chrome']

34

});

35

};

36

```

37

38

With Mocha configuration options:

39

40

```javascript

41

// karma.conf.js - With Mocha options

42

module.exports = function(config) {

43

config.set({

44

frameworks: ['mocha'],

45

files: ['test/**/*.spec.js'],

46

browsers: ['Chrome'],

47

client: {

48

mocha: {

49

ui: 'bdd',

50

timeout: 5000,

51

reporter: 'html'

52

}

53

}

54

});

55

};

56

```

57

58

## Architecture

59

60

karma-mocha works as a bridge between two testing systems:

61

62

- **Karma Framework Integration**: Registers as a Karma framework plugin that automatically sets up the test environment

63

- **File Injection**: Automatically includes Mocha library files, CSS, and adapter scripts into the Karma test environment

64

- **Configuration Processing**: Processes Mocha configuration options from Karma config and mocha.opts files

65

- **Result Reporting**: Translates Mocha test results into Karma's result format with detailed metadata

66

- **Browser Compatibility**: Provides polyfills and utilities for cross-browser test execution

67

68

## Capabilities

69

70

### Framework Registration

71

72

The plugin automatically registers with Karma as the 'mocha' framework.

73

74

```javascript { .api }

75

/**

76

* Karma framework plugin registration

77

* Automatically called by Karma when 'mocha' is specified in frameworks array

78

*/

79

const frameworkPlugin = {

80

'framework:mocha': ['factory', initMocha]

81

};

82

```

83

84

### Mocha Integration

85

86

Core function that sets up Mocha within the Karma environment.

87

88

```javascript { .api }

89

/**

90

* Initialize Mocha framework integration with Karma

91

* @param files - Karma files array to inject Mocha dependencies

92

* @param config - Karma configuration object

93

*/

94

function initMocha(files, config);

95

```

96

97

### Configuration Processing

98

99

Processes and normalizes Mocha configuration options.

100

101

```javascript { .api }

102

/**

103

* Process Mocha configuration options including loading from mocha.opts files

104

* @param mochaConfig - Mocha configuration object

105

* @returns Normalized configuration object with supported Mocha options

106

*/

107

function getMochaOpts(mochaConfig);

108

```

109

110

### Configuration Options

111

112

The following Mocha options are supported via `client.mocha` in Karma configuration:

113

114

```javascript { .api }

115

interface MochaConfig {

116

/** Mocha reporter to use (e.g., 'html', 'dot') */

117

reporter?: string;

118

/** Mocha user interface (e.g., 'bdd', 'tdd') */

119

ui?: string;

120

/** Files to require before running tests */

121

require?: string[];

122

/** Global variables to allow in tests */

123

globals?: string[];

124

/** Pattern to filter tests */

125

grep?: string | RegExp;

126

/** Test timeout in milliseconds */

127

timeout?: number;

128

/** Slow test threshold in milliseconds */

129

slow?: number;

130

/** Stop running tests after first failure */

131

bail?: boolean;

132

/** Ignore global variable leaks */

133

ignoreLeaks?: boolean;

134

/** Path to mocha.opts file or true for default location */

135

opts?: string | boolean;

136

/** Test properties to expose in test results */

137

expose?: string[];

138

}

139

```

140

141

**Configuration Examples:**

142

143

```javascript

144

// Basic Mocha configuration

145

client: {

146

mocha: {

147

ui: 'bdd',

148

timeout: 10000,

149

reporter: 'html'

150

}

151

}

152

153

// With grep pattern filtering

154

client: {

155

mocha: {

156

grep: 'integration',

157

bail: true

158

}

159

}

160

161

// With custom requires and exposed properties

162

client: {

163

mocha: {

164

require: ['should', './test/helpers.js'],

165

expose: ['body', 'state']

166

}

167

}

168

169

// Using mocha.opts file

170

client: {

171

mocha: {

172

opts: 'test/mocha.opts' // or true for default 'test/mocha.opts'

173

}

174

}

175

```

176

177

### Test Result Reporting

178

179

Transforms Mocha test results into Karma's expected format.

180

181

```javascript { .api }

182

/**

183

* Report individual test result to Karma

184

* @param karma - Karma test context

185

* @param test - Mocha test object

186

*/

187

function reportTestResult(karma, test);

188

189

interface KarmaTestResult {

190

/** Test ID (empty string) */

191

id: string;

192

/** Test title */

193

description: string;

194

/** Array of parent suite titles */

195

suite: string[];

196

/** True if test passed */

197

success: boolean;

198

/** True if test was skipped */

199

skipped: boolean;

200

/** True if test is pending (same as skipped) */

201

pending: boolean;

202

/** Test duration in milliseconds */

203

time: number;

204

/** Array of error messages */

205

log: string[];

206

/** Array of detailed assertion error objects */

207

assertionErrors: AssertionError[];

208

/** Test start timestamp */

209

startTime: number;

210

/** Test end timestamp */

211

endTime: number;

212

/** Optional exposed Mocha properties (if configured) */

213

mocha?: Record<string, any>;

214

}

215

216

interface AssertionError {

217

/** Error name */

218

name: string;

219

/** Error message */

220

message: string;

221

/** Actual data in assertion, serialized to string */

222

actual?: string;

223

/** Expected data in assertion, serialized to string */

224

expected?: string;

225

/** True if configured to show diff */

226

showDiff?: boolean;

227

}

228

```

229

230

### Custom Reporter Creation

231

232

Creates Mocha reporter tailored for Karma integration.

233

234

```javascript { .api }

235

/**

236

* Create custom Mocha reporter constructor for Karma integration

237

* @param karma - Karma test context

238

* @param pathname - Window location pathname

239

* @returns Mocha reporter constructor function

240

*/

241

function createMochaReporterConstructor(karma, pathname);

242

```

243

244

### Test Execution

245

246

Handles Mocha test execution with command-line argument support.

247

248

```javascript { .api }

249

/**

250

* Create start function for Mocha test execution with grep support

251

* @param mocha - Mocha instance

252

* @returns Function to start test execution with configuration

253

*/

254

function createMochaStartFn(mocha);

255

256

/**

257

* Create Mocha configuration object from Karma config

258

* Note: Filters out 'reporter', 'require', and 'expose' properties

259

* @param karma - Karma context with configuration

260

* @returns Mocha configuration object

261

*/

262

function createConfigObject(karma);

263

```

264

265

## Error Handling

266

267

The adapter provides enhanced error formatting and processing:

268

269

```javascript { .api }

270

/**

271

* Format test errors, removing Mocha stack entries

272

* @param error - Error object from test failure

273

* @returns Formatted error string

274

*/

275

function formatError(error);

276

277

/**

278

* Process assertion errors for better reporting with diff support

279

* @param error - Assertion error object

280

* @returns Processed error object with diff information

281

*/

282

function processAssertionError(error);

283

```

284

285

## Utility Functions

286

287

Internal utility functions that support the adapter functionality:

288

289

```javascript { .api }

290

/**

291

* Create Karma file pattern object for dependency injection

292

* @param path - File path to include

293

* @returns Karma pattern object with default options

294

*/

295

function createPattern(path);

296

297

/**

298

* Check if Karma configuration contains Mocha options

299

* @param karma - Karma context object

300

* @returns True if mocha configuration exists

301

*/

302

function haveMochaConfig(karma);

303

304

/**

305

* Create DOM node for Mocha reporter in debug mode

306

* Creates div element with id='mocha' and appends to document.body

307

*/

308

function createMochaReporterNode();

309

310

/**

311

* Polyfill for Array.prototype.includes compatibility

312

* @param collection - Array or string to search

313

* @param element - Element to find

314

* @param startIndex - Starting search index

315

* @returns True if element is found

316

*/

317

function includes(collection, element, startIndex);

318

319

/**

320

* Polyfill for Array.prototype.reduce functionality

321

* @param array - Array to reduce

322

* @param reducer - Reducer function

323

* @param memo - Initial accumulator value

324

* @returns Final reduced value

325

*/

326

function arrayReduce(array, reducer, memo);

327

```

328

329

## Command Line Integration

330

331

karma-mocha supports Mocha's grep functionality through Karma's command line:

332

333

```bash

334

# Run only tests matching pattern

335

karma start &

336

karma run -- --grep="integration tests"

337

338

# Or with specific pattern format

339

karma run -- --grep=unit

340

```

341

342

## Browser Compatibility

343

344

The adapter includes compatibility features:

345

346

- **Array.prototype.includes polyfill**: For older browsers

347

- **Date.now polyfill**: For IE <= 8

348

- **Cross-browser DOM manipulation**: For reporter node creation

349

350

## Integration Notes

351

352

- **Dependencies**: Minimal dependency footprint - only requires `minimist` as a runtime dependency

353

- **Peer Dependencies**: Requires both `karma` and `mocha` to be installed

354

- **Automatic Setup**: No manual initialization required - works through Karma's plugin system

355

- **File Order**: Automatically manages loading order of Mocha files, CSS, and adapter scripts

356

- **Coverage Support**: Compatible with Karma coverage plugins (reports `window.__coverage__`)

357

- **Debug Mode**: Provides enhanced error display in Karma's debug.html page

358

- **Configuration Filtering**: Automatically filters out internal options (`reporter`, `require`, `expose`) when creating Mocha config