0
# Test Execution
1
2
Mocha test runner with console log detection, configuration merging, and enhanced error reporting for LoopBack projects.
3
4
## Capabilities
5
6
### lb-mocha Command
7
8
Runs Mocha tests with automatic configuration discovery and console log detection.
9
10
```typescript { .api }
11
/**
12
* Mocha test runner function with enhanced features
13
* @param argv - Command line arguments including test files and options
14
* @param options - Execution options for dry run and process control
15
* @returns ChildProcess when executed, string when dry run
16
*/
17
function mocha(argv: string[], options?: RunOptions): ChildProcess | string;
18
```
19
20
**CLI Usage:**
21
22
```bash
23
# Run all tests
24
lb-mocha
25
26
# Run specific test files
27
lb-mocha "dist/__tests__/**/*.js"
28
29
# Run tests with custom timeout
30
lb-mocha --timeout 5000 "dist/__tests__"
31
32
# Allow console logs in tests
33
lb-mocha --allow-console-logs "dist/__tests__"
34
35
# Set language for tests
36
lb-mocha --lang en_US.UTF-8 "dist/__tests__"
37
38
# Run with custom configuration
39
lb-mocha --config .mocharc.custom.json
40
```
41
42
**Programmatic Usage:**
43
44
```typescript
45
import { mocha } from "@loopback/build";
46
47
// Run tests with default settings
48
const child = mocha(["dist/__tests__"]);
49
50
// Dry run to see command
51
const command = mocha(["--timeout", "10000", "dist/__tests__"], { dryRun: true });
52
console.log(command); // Shows the Mocha command that would be executed
53
54
// Run tests in custom directory
55
mocha(["test/"], { cwd: "/path/to/project" });
56
```
57
58
### Configuration Discovery
59
60
Automatically discovers Mocha configuration files in the project.
61
62
**Configuration Search Order:**
63
1. `.mocharc.js` in project root
64
2. `.mocharc.json` in project root
65
3. `.mocharc.yaml` in project root
66
4. `.mocharc.yml` in project root
67
5. Falls back to `@loopback/build/config/.mocharc.json`
68
69
**Default Configuration:**
70
71
```typescript { .api }
72
// @loopback/build/config/.mocharc.json contents:
73
interface MochaConfig {
74
require: ["source-map-support/register"];
75
recursive: true;
76
exit: true;
77
reporter: "dot";
78
}
79
```
80
81
### Console Log Detection
82
83
Advanced feature that detects and fails tests when unexpected console output occurs.
84
85
```typescript { .api }
86
/**
87
* Console log detection hooks for Mocha
88
* Automatically injected unless --allow-console-logs is specified
89
*/
90
interface MochaHooks {
91
beforeAll: () => void; // Start recording console logs
92
beforeEach: () => void; // Save current test context
93
afterEach: () => void; // Check for test failures
94
afterAll: () => void; // Report console log problems
95
}
96
```
97
98
**Features:**
99
- Intercepts `console.log`, `console.error`, and `console.warn`
100
- Allows Mocha reporter console output
101
- Ignores console logs from failed tests (for debugging)
102
- Provides detailed stack traces for console log sources
103
- Fails test suite if unexpected console logs are detected
104
105
**Disabling Console Log Detection:**
106
107
```bash
108
# Allow console logs in tests
109
lb-mocha --allow-console-logs "dist/__tests__"
110
```
111
112
### Configuration Merging
113
114
Utility for merging multiple Mocha configuration objects.
115
116
```typescript { .api }
117
/**
118
* Merge multiple Mocha configuration objects with smart handling
119
* @param configs - Array of Mocha configuration objects
120
* @returns Merged configuration with combined require arrays and max timeout
121
*/
122
function mergeMochaConfigs(...configs: MochaConfig[]): MochaConfig;
123
124
interface MochaConfig {
125
timeout?: number; // Test timeout in milliseconds
126
require?: string | string[]; // Files to require before tests
127
reporter?: string; // Test reporter to use
128
recursive?: boolean; // Search subdirectories for tests
129
exit?: boolean; // Force exit after tests complete
130
[key: string]: any; // Additional Mocha options
131
}
132
```
133
134
**Merging Behavior:**
135
- `timeout`: Uses maximum value from all configs
136
- `require`: Combines all require arrays into single array
137
- Other properties: Later configs override earlier ones
138
139
**Usage Example:**
140
141
```typescript
142
import { mergeMochaConfigs } from "@loopback/build";
143
144
const baseConfig = {
145
timeout: 2000,
146
require: ["source-map-support/register"],
147
reporter: "spec"
148
};
149
150
const projectConfig = {
151
timeout: 5000,
152
require: ["./test/setup.js"],
153
recursive: true
154
};
155
156
const merged = mergeMochaConfigs(baseConfig, projectConfig);
157
// Result:
158
// {
159
// timeout: 5000, // Max of 2000 and 5000
160
// require: ["source-map-support/register", "./test/setup.js"],
161
// reporter: "spec",
162
// recursive: true
163
// }
164
```
165
166
### Language and Environment Support
167
168
Supports custom language settings and environment variables.
169
170
```typescript { .api }
171
// --lang option sets LANG environment variable
172
// Useful for locale-specific test behavior
173
```
174
175
**Usage:**
176
177
```bash
178
# Set language for tests
179
lb-mocha --lang en_US.UTF-8 "dist/__tests__"
180
181
# This sets process.env.LANG = "en_US.UTF-8" before running tests
182
```
183
184
### Node.js Warning Suppression
185
186
Automatically suppresses Node.js warnings during test execution.
187
188
```typescript { .api }
189
// Automatically adds --no-warnings flag to Node.js
190
// Prevents deprecation warnings from cluttering test output
191
// Only applied when console log detection is enabled
192
```
193
194
### Command Line Option Passthrough
195
196
All Mocha command line options are supported and passed through.
197
198
```typescript { .api }
199
interface MochaOptions {
200
"--config": string; // Configuration file path
201
"--package": string; // package.json file path
202
"--no-config": boolean; // Ignore configuration files
203
"--timeout": number; // Test timeout in milliseconds
204
"--reporter": string; // Test reporter
205
"--grep": string; // Only run tests matching pattern
206
"--fgrep": string; // Only run tests containing string
207
"--invert": boolean; // Invert grep/fgrep matches
208
"--recursive": boolean; // Search subdirectories
209
"--exit": boolean; // Force exit after completion
210
"--bail": boolean; // Stop on first failure
211
"--slow": number; // Slow test threshold
212
"--require": string; // Require module before running
213
"--reporter-options": string; // Reporter-specific options
214
"--parallel": boolean; // Run tests in parallel
215
"--jobs": number; // Number of parallel jobs
216
}
217
```
218
219
### Usage Examples
220
221
**Basic Test Execution:**
222
223
```typescript
224
import { mocha, mergeMochaConfigs } from "@loopback/build";
225
226
// Run tests with default configuration
227
mocha(["dist/__tests__"], { dryRun: false });
228
229
// Merge custom configuration
230
const config = mergeMochaConfigs(
231
{ timeout: 2000, reporter: "spec" },
232
{ timeout: 5000, require: ["./test/setup.js"] }
233
);
234
```
235
236
**Package.json Integration:**
237
238
```json
239
{
240
"scripts": {
241
"test": "lb-mocha \"dist/__tests__\"",
242
"test:watch": "lb-mocha --watch \"dist/__tests__\"",
243
"test:debug": "lb-mocha --allow-console-logs --timeout 0 \"dist/__tests__\"",
244
"test:coverage": "lb-nyc lb-mocha \"dist/__tests__\""
245
}
246
}
247
```
248
249
**Custom Configuration Files:**
250
251
```javascript
252
// .mocharc.js
253
module.exports = {
254
timeout: 10000,
255
require: ["source-map-support/register", "./test/setup.js"],
256
reporter: "spec",
257
recursive: true,
258
exit: true
259
};
260
```
261
262
### Error Handling and Reporting
263
264
Enhanced error handling with detailed console log reporting.
265
266
```typescript { .api }
267
// Console log detection provides detailed error messages
268
// Stack traces show exact location of console.log calls
269
// Test failures are properly reported with context
270
// Process exits with appropriate error codes
271
```
272
273
**Console Log Error Format:**
274
```
275
=== ATTENTION - INVALID USAGE OF CONSOLE LOGS DETECTED ===
276
Learn more at https://github.com/loopbackio/loopback-next/blob/master/packages/build/README.md#a-note-on-console-logs-printed-by-tests
277
278
Unexpected console.log() call
279
at MyClass.method (/path/to/file.js:123:45)
280
at Test.myTest (/path/to/test.js:67:89)
281
```