or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdindex.mdmock-builder.mdmock-creation.mdmock-instance.mdmock-render.mdtesting-utilities.md

configuration.mddocs/

0

# Configuration and Global Settings

1

2

Global configuration system for default behaviors, spy integration, and testing framework compatibility. Provides comprehensive control over ng-mocks behavior across all tests.

3

4

## Capabilities

5

6

### Spy Framework Integration

7

8

Configure automatic spy creation for different testing frameworks.

9

10

```typescript { .api }

11

/**

12

* Configures automatic spy creation for different frameworks

13

* @param type - Framework type or 'reset' to disable

14

*/

15

function autoSpy(type: 'jasmine' | 'jest' | 'default' | 'reset'): void;

16

17

/**

18

* Configures automatic spy creation with custom function

19

* @param type - Custom spy factory function

20

*/

21

function autoSpy(type: CustomMockFunction): void;

22

23

/**

24

* Custom spy factory function type

25

*/

26

type CustomMockFunction = (mockName: string) => MockedFunction;

27

type MockedFunction = (...args: any[]) => any;

28

```

29

30

**Usage Examples:**

31

32

```typescript

33

import { ngMocks } from "ng-mocks";

34

35

// Configure for Jasmine

36

ngMocks.autoSpy('jasmine');

37

38

// Configure for Jest

39

ngMocks.autoSpy('jest');

40

41

// Custom spy factory

42

ngMocks.autoSpy((name: string) => {

43

const spy = jasmine.createSpy(name);

44

spy.and.returnValue(undefined);

45

return spy;

46

});

47

48

// Disable auto-spy

49

ngMocks.autoSpy('reset');

50

```

51

52

### Default Mock Configuration

53

54

Set default configurations and behaviors for mock declarations.

55

56

```typescript { .api }

57

/**

58

* Sets default configuration for a declaration type

59

* @param token - Declaration class or string token

60

* @param config - Default MockBuilder configuration

61

*/

62

function defaultConfig<T>(token: string | AnyDeclaration<T>, config?: IMockBuilderConfig): void;

63

64

/**

65

* Sets default mock behavior for injection tokens

66

* @param token - InjectionToken to configure

67

* @param handler - Function to customize mock instances

68

* @param config - Additional configuration

69

*/

70

function defaultMock<T>(

71

token: InjectionToken<T>,

72

handler?: (value: undefined | T, injector: Injector) => undefined | Partial<T>,

73

config?: IMockBuilderConfig

74

): void;

75

76

/**

77

* Sets default mock behavior for string tokens

78

* @param token - String token to configure

79

* @param handler - Function to customize mock instances

80

* @param config - Additional configuration

81

*/

82

function defaultMock<T = any>(

83

token: string,

84

handler?: (value: undefined | T, injector: Injector) => undefined | Partial<T>,

85

config?: IMockBuilderConfig

86

): void;

87

88

/**

89

* Sets default mock behavior for declaration classes

90

* @param def - Declaration class to configure

91

* @param handler - Function to customize mock instances

92

* @param config - Additional configuration

93

*/

94

function defaultMock<T>(

95

def: AnyType<T>,

96

handler?: (value: T, injector: Injector) => void | Partial<T>,

97

config?: IMockBuilderConfig

98

): void;

99

100

/**

101

* Sets default mock behavior for multiple declarations

102

* @param defs - Array of declarations to configure

103

* @param handler - Function to customize mock instances

104

* @param config - Additional configuration

105

*/

106

function defaultMock<T = any>(

107

defs: Array<AnyDeclaration<T>>,

108

handler?: (value: undefined | T, injector: Injector) => undefined | Partial<T>,

109

config?: IMockBuilderConfig

110

): void;

111

```

112

113

**Usage Examples:**

114

115

```typescript

116

import { ngMocks } from "ng-mocks";

117

118

// Set default configuration flags

119

ngMocks.defaultConfig(MyComponent, { shallow: true });

120

ngMocks.defaultConfig(SharedModule, { exportAll: true });

121

122

// Set default mock behavior for services

123

ngMocks.defaultMock(AuthService, (instance) => ({

124

isAuthenticated: true,

125

user: { id: 1, name: 'Test User' }

126

}));

127

128

// Configure injection tokens

129

ngMocks.defaultMock(API_URL, () => 'http://localhost:3000');

130

131

// Configure multiple services at once

132

ngMocks.defaultMock([UserService, OrderService], (instance, injector) => {

133

const httpClient = injector.get(HttpClient);

134

return {

135

http: httpClient,

136

loading: false

137

};

138

});

139

```

140

141

### Global Declaration Management

142

143

Configure which declarations should always be kept, mocked, or excluded across all tests.

144

145

```typescript { .api }

146

/**

147

* Globally excludes declarations from all mocks

148

* @param source - Declaration to exclude

149

* @param recursively - Whether to apply recursively to dependencies

150

*/

151

function globalExclude(source: AnyDeclaration<any>, recursively?: boolean): void;

152

153

/**

154

* Globally keeps declarations in all mocks (never mock them)

155

* @param source - Declaration to keep

156

* @param recursively - Whether to apply recursively to dependencies

157

*/

158

function globalKeep(source: AnyDeclaration<any>, recursively?: boolean): void;

159

160

/**

161

* Globally mocks declarations even when they would be kept

162

* @param source - Declaration to mock

163

* @param recursively - Whether to apply recursively to dependencies

164

*/

165

function globalMock(source: AnyDeclaration<any>, recursively?: boolean): void;

166

167

/**

168

* Globally replaces one declaration with another across all mocks

169

* @param source - Declaration to replace

170

* @param destination - Replacement declaration

171

*/

172

function globalReplace(source: AnyType<any>, destination: AnyType<any>): void;

173

174

/**

175

* Removes global configuration for a declaration

176

* @param source - Declaration to reset

177

* @param recursively - Whether to apply recursively to dependencies

178

*/

179

function globalWipe(source: AnyDeclaration<any>, recursively?: boolean): void;

180

```

181

182

**Usage Examples:**

183

184

```typescript

185

import { ngMocks } from "ng-mocks";

186

187

// Always keep common Angular modules

188

ngMocks.globalKeep(CommonModule, true);

189

ngMocks.globalKeep(FormsModule, true);

190

ngMocks.globalKeep(ReactiveFormsModule, true);

191

192

// Always mock HTTP-related modules

193

ngMocks.globalMock(HttpClientModule, true);

194

195

// Always exclude problematic modules

196

ngMocks.globalExclude(ProblematicThirdPartyModule, true);

197

198

// Global replacements for testing

199

ngMocks.globalReplace(BrowserAnimationsModule, NoopAnimationsModule);

200

201

// Remove global configuration

202

ngMocks.globalWipe(HttpClientModule);

203

ngMocks.globalWipe(CommonModule, true);

204

```

205

206

### System Configuration

207

208

Configure ng-mocks behavior and error handling.

209

210

```typescript { .api }

211

/**

212

* Configures ng-mocks system behavior

213

* @param config - Configuration object

214

*/

215

function config(config: {

216

/** Maximum number of MockRender fixtures to cache (null = unlimited) */

217

mockRenderCacheSize?: number | null;

218

/** Behavior when MockBuilder encounters missing dependencies */

219

onMockBuilderMissingDependency?: 'throw' | 'warn' | 'i-know-but-disable' | null;

220

/** Behavior when MockInstance restore is needed */

221

onMockInstanceRestoreNeed?: 'throw' | 'warn' | 'i-know-but-disable' | null;

222

/** Behavior when TestBed flush is needed */

223

onTestBedFlushNeed?: 'throw' | 'warn' | 'i-know-but-disable' | null;

224

}): void;

225

```

226

227

**Usage Examples:**

228

229

```typescript

230

import { ngMocks } from "ng-mocks";

231

232

// Configure for production-like testing

233

ngMocks.config({

234

mockRenderCacheSize: 10,

235

onMockBuilderMissingDependency: 'warn',

236

onMockInstanceRestoreNeed: 'warn',

237

onTestBedFlushNeed: 'throw'

238

});

239

240

// Disable cache for memory-constrained environments

241

ngMocks.config({

242

mockRenderCacheSize: 0

243

});

244

245

// Strict mode - fail fast on issues

246

ngMocks.config({

247

onMockBuilderMissingDependency: 'throw',

248

onMockInstanceRestoreNeed: 'throw',

249

onTestBedFlushNeed: 'throw'

250

});

251

```

252

253

### Console and Error Handling

254

255

Control console output and error handling during tests.

256

257

```typescript { .api }

258

/**

259

* Suppresses console methods during tests

260

* @param args - Console method names to suppress

261

*/

262

function ignoreOnConsole(...args: Array<keyof typeof console>): void;

263

264

/**

265

* Causes console methods to throw errors during tests

266

* @param args - Console method names to make throw

267

*/

268

function throwOnConsole(...args: Array<keyof typeof console>): void;

269

```

270

271

**Usage Examples:**

272

273

```typescript

274

import { ngMocks } from "ng-mocks";

275

276

// Suppress console warnings and logs during tests

277

ngMocks.ignoreOnConsole('warn', 'log');

278

279

// Make console errors throw exceptions

280

ngMocks.throwOnConsole('error');

281

282

// Ignore all console output

283

ngMocks.ignoreOnConsole('log', 'warn', 'error', 'info', 'debug');

284

```

285

286

### Performance and Caching

287

288

Optimize performance with caching and reuse strategies.

289

290

```typescript { .api }

291

/**

292

* Enables TestBed reuse between tests for better performance

293

*/

294

function faster(): void;

295

296

/**

297

* Resets ng-mocks internal cache

298

*/

299

function reset(): void;

300

301

/**

302

* Flushes TestBed state

303

*/

304

function flushTestBed(): void;

305

```

306

307

**Usage Examples:**

308

309

```typescript

310

import { ngMocks } from "ng-mocks";

311

312

// Enable faster test execution

313

beforeAll(() => {

314

ngMocks.faster();

315

});

316

317

// Reset between test suites

318

afterAll(() => {

319

ngMocks.reset();

320

ngMocks.flushTestBed();

321

});

322

323

// Clean up in specific tests

324

afterEach(() => {

325

if (testNeedsCleanup) {

326

ngMocks.flushTestBed();

327

}

328

});

329

```

330

331

### Configuration Patterns

332

333

Common configuration patterns for different testing scenarios.

334

335

**Basic Test Setup:**

336

337

```typescript

338

// spec-helper.ts or test setup file

339

import { ngMocks } from "ng-mocks";

340

341

// Configure spy framework

342

ngMocks.autoSpy('jasmine');

343

344

// Global module configuration

345

ngMocks.globalKeep(CommonModule, true);

346

ngMocks.globalKeep(FormsModule, true);

347

ngMocks.globalReplace(BrowserAnimationsModule, NoopAnimationsModule);

348

349

// Suppress non-critical console output

350

ngMocks.ignoreOnConsole('warn');

351

352

// Enable performance optimizations

353

ngMocks.faster();

354

```

355

356

**Enterprise Application Setup:**

357

358

```typescript

359

// Configure for large applications

360

ngMocks.config({

361

mockRenderCacheSize: 50,

362

onMockBuilderMissingDependency: 'warn'

363

});

364

365

// Always keep core modules

366

ngMocks.globalKeep(SharedModule, true);

367

ngMocks.globalKeep(CoreModule, true);

368

ngMocks.globalKeep(MaterialModule, true);

369

370

// Mock external service modules

371

ngMocks.globalMock(HttpClientModule, true);

372

ngMocks.globalMock(AngularFireModule, true);

373

374

// Standard service mocks

375

ngMocks.defaultMock(AuthService, () => ({

376

isAuthenticated: true,

377

user: { id: 1, name: 'Test User', role: 'user' }

378

}));

379

380

ngMocks.defaultMock(ConfigService, () => ({

381

apiUrl: 'http://localhost:3000',

382

environment: 'test'

383

}));

384

```

385

386

**Library Testing Setup:**

387

388

```typescript

389

// Configure for library testing

390

ngMocks.config({

391

onMockBuilderMissingDependency: 'throw', // Strict dependency checking

392

onTestBedFlushNeed: 'throw'

393

});

394

395

// Keep only Angular core modules

396

ngMocks.globalKeep(CommonModule);

397

ngMocks.globalKeep(FormsModule);

398

399

// Mock everything else

400

ngMocks.globalMock(HttpClientModule, true);

401

ngMocks.globalMock(RouterModule, true);

402

```

403

404

**Integration Test Setup:**

405

406

```typescript

407

// More permissive for integration tests

408

ngMocks.config({

409

onMockBuilderMissingDependency: 'i-know-but-disable',

410

mockRenderCacheSize: 5 // Lower cache for integration tests

411

});

412

413

// Keep more real modules for integration

414

ngMocks.globalKeep(HttpClientModule);

415

ngMocks.globalKeep(RouterModule);

416

ngMocks.globalKeep(SharedModule, true);

417

418

// Only mock external dependencies

419

ngMocks.globalMock(ThirdPartyApiModule, true);

420

```