0
# Testing Utilities and Helpers
1
2
Comprehensive testing utilities through the ngMocks object. Provides DOM interaction, element queries, instance access, event handling, and validation helpers for Angular testing.
3
4
## Capabilities
5
6
### Element Query Methods
7
8
Find and query DOM elements and components in test fixtures.
9
10
```typescript { .api }
11
/**
12
* Finds the first DebugElement of a component type
13
* @param component - Component class to find
14
* @param notFoundValue - Value to return if not found
15
* @returns Found DebugElement or notFoundValue
16
*/
17
function find<T>(component: Type<T>): MockedDebugElement<T>;
18
function find<T, D>(component: Type<T>, notFoundValue: D): D | MockedDebugElement<T>;
19
20
/**
21
* Finds the first DebugElement of a component type within a root element
22
* @param debugElement - Root element to search within
23
* @param component - Component class to find
24
* @param notFoundValue - Value to return if not found
25
* @returns Found DebugElement or notFoundValue
26
*/
27
function find<T>(
28
debugElement: MockedDebugElement | ComponentFixture<any> | undefined | null,
29
component: Type<T>
30
): MockedDebugElement<T>;
31
function find<T, D>(
32
debugElement: MockedDebugElement | ComponentFixture<any> | undefined | null,
33
component: Type<T>,
34
notFoundValue: D
35
): D | MockedDebugElement<T>;
36
37
/**
38
* Finds the first DebugElement matching a CSS selector
39
* @param cssSelector - CSS selector string or attribute selector
40
* @param notFoundValue - Value to return if not found
41
* @returns Found DebugElement or notFoundValue
42
*/
43
function find<T = any>(
44
cssSelector: string | [string] | [string, string | number]
45
): MockedDebugElement<T>;
46
function find<T = any, D = undefined>(
47
cssSelector: string | [string] | [string, string | number],
48
notFoundValue: D
49
): D | MockedDebugElement<T>;
50
51
/**
52
* Finds all DebugElements of a component type
53
* @param component - Component class to find
54
* @returns Array of found DebugElements
55
*/
56
function findAll<T>(component: Type<T>): Array<MockedDebugElement<T>>;
57
function findAll<T>(
58
debugElement: MockedDebugElement | ComponentFixture<any> | undefined | null,
59
component: Type<T>
60
): Array<MockedDebugElement<T>>;
61
62
/**
63
* Finds all DebugElements matching a CSS selector
64
* @param cssSelector - CSS selector string or attribute selector
65
* @returns Array of found DebugElements
66
*/
67
function findAll<T = any>(
68
cssSelector: string | [string] | [string, string | number]
69
): Array<MockedDebugElement<T>>;
70
function findAll<T = any>(
71
debugElement: MockedDebugElement | ComponentFixture<any> | undefined | null,
72
cssSelector: string | [string] | [string, string | number]
73
): Array<MockedDebugElement<T>>;
74
```
75
76
**Usage Examples:**
77
78
```typescript
79
import { ngMocks } from "ng-mocks";
80
81
// Find component by type
82
const headerEl = ngMocks.find(HeaderComponent);
83
const headerInstance = headerEl.componentInstance;
84
85
// Find with fallback
86
const sidebarEl = ngMocks.find(SidebarComponent, null);
87
if (sidebarEl) {
88
// Handle found element
89
}
90
91
// Find by CSS selector
92
const buttonEl = ngMocks.find('button.primary');
93
const linkEls = ngMocks.findAll('a[href]');
94
95
// Find by attribute
96
const dataEl = ngMocks.find(['data-testid', 'user-info']);
97
const allDataEls = ngMocks.findAll(['data-role']);
98
99
// Search within specific element
100
const nestedEl = ngMocks.find(fixture.debugElement, MyComponent);
101
```
102
103
### Instance Access Methods
104
105
Access component instances and injected services.
106
107
```typescript { .api }
108
/**
109
* Gets an instance of a declaration from an element
110
* @param elSelector - Element selector
111
* @param provider - Declaration class or token
112
* @param notFoundValue - Value to return if not found
113
* @returns Instance or notFoundValue
114
*/
115
function get<T>(elSelector: DebugNodeSelector, provider: AnyDeclaration<T>): T;
116
function get<T, D>(
117
elSelector: DebugNodeSelector,
118
provider: AnyDeclaration<T>,
119
notFoundValue: D
120
): D | T;
121
122
/**
123
* Gets an instance from TestBed
124
* @param provider - Declaration class or token
125
* @returns Instance from TestBed
126
*/
127
function get<T>(provider: AnyDeclaration<T>): T;
128
129
/**
130
* Finds the first instance of a declaration in the component tree
131
* @param instanceClass - Declaration class or token
132
* @param notFoundValue - Value to return if not found
133
* @returns Found instance or notFoundValue
134
*/
135
function findInstance<T>(instanceClass: AnyDeclaration<T>): T;
136
function findInstance<T, D>(instanceClass: AnyDeclaration<T>, notFoundValue: D): D | T;
137
function findInstance<T>(
138
elSelector: DebugNodeSelector,
139
instanceClass: AnyDeclaration<T>
140
): T;
141
function findInstance<T, D>(
142
elSelector: DebugNodeSelector,
143
instanceClass: AnyDeclaration<T>,
144
notFoundValue: D
145
): D | T;
146
147
/**
148
* Finds all instances of a declaration in the component tree
149
* @param instanceClass - Declaration class or token
150
* @returns Array of found instances
151
*/
152
function findInstances<T>(instanceClass: AnyDeclaration<T>): T[];
153
function findInstances<T>(
154
elSelector: DebugNodeSelector,
155
instanceClass: AnyDeclaration<T>
156
): T[];
157
```
158
159
**Usage Examples:**
160
161
```typescript
162
import { ngMocks } from "ng-mocks";
163
164
// Get service from TestBed
165
const authService = ngMocks.get(AuthService);
166
167
// Get component instance from element
168
const headerEl = ngMocks.find(HeaderComponent);
169
const headerService = ngMocks.get(headerEl, HeaderService);
170
171
// Find service instance anywhere in component tree
172
const dataService = ngMocks.findInstance(DataService);
173
174
// Find with fallback
175
const optionalService = ngMocks.findInstance(OptionalService, null);
176
177
// Find all instances
178
const allServices = ngMocks.findInstances(LoggingService);
179
```
180
181
### Input and Output Access
182
183
Access component inputs and outputs without knowing the specific component.
184
185
```typescript { .api }
186
/**
187
* Gets an input value from a component
188
* @param elSelector - Element selector
189
* @param input - Input property name
190
* @param notFoundValue - Value to return if not found
191
* @returns Input value or notFoundValue
192
*/
193
function input<T = any>(elSelector: DebugNodeSelector, input: string): T;
194
function input<T = any, D = undefined>(
195
elSelector: DebugNodeSelector,
196
input: string,
197
notFoundValue: D
198
): D | T;
199
200
/**
201
* Gets an output EventEmitter from a component
202
* @param elSelector - Element selector
203
* @param output - Output property name
204
* @param notFoundValue - Value to return if not found
205
* @returns EventEmitter or notFoundValue
206
*/
207
function output<T = any>(elSelector: DebugNodeSelector, output: string): EventEmitter<T>;
208
function output<T = any, D = undefined>(
209
elSelector: DebugNodeSelector,
210
output: string,
211
notFoundValue: D
212
): D | EventEmitter<T>;
213
```
214
215
**Usage Examples:**
216
217
```typescript
218
import { ngMocks } from "ng-mocks";
219
220
// Get input values
221
const userEl = ngMocks.find(UserComponent);
222
const userName = ngMocks.input(userEl, 'name');
223
const userAge = ngMocks.input(userEl, 'age', 0);
224
225
// Get output emitters
226
const clickEmitter = ngMocks.output(userEl, 'click');
227
const changeEmitter = ngMocks.output(userEl, 'change', null);
228
229
// Subscribe to outputs
230
clickEmitter.subscribe(data => {
231
console.log('User clicked:', data);
232
});
233
```
234
235
### DOM Interaction Methods
236
237
Interact with DOM elements and trigger events.
238
239
```typescript { .api }
240
/**
241
* Simulates a click on an element
242
* @param elSelector - Element or selector
243
* @param payload - Optional mouse event properties
244
*/
245
function click(
246
elSelector: HTMLElement | DebugNodeSelector,
247
payload?: Partial<MouseEvent>
248
): void;
249
250
/**
251
* Triggers a custom event on an element
252
* @param elSelector - Element or selector
253
* @param event - Event object or event name
254
* @param payload - Optional event properties
255
*/
256
function trigger(elSelector: DebugNodeSelector, event: Event): void;
257
function trigger(
258
elSelector: HTMLElement | DebugNodeSelector,
259
event: string,
260
payload?: Partial<UIEvent | KeyboardEvent | MouseEvent | TouchEvent>
261
): void;
262
263
/**
264
* Creates properly formatted events
265
* @param event - Event type string
266
* @param init - Event initialization options
267
* @param overrides - Property overrides
268
* @returns Created event object
269
*/
270
function event(
271
event: string,
272
init?: EventInit,
273
overrides?: Partial<UIEvent | KeyboardEvent | MouseEvent | TouchEvent | Event>
274
): Event;
275
276
/**
277
* Triggers ControlValueAccessor changes
278
* @param elSelector - Element selector
279
* @param value - New value
280
* @param methodName - CVA method name to call
281
*/
282
function change(elSelector: DebugNodeSelector, value: any, methodName?: string): void;
283
284
/**
285
* Triggers ControlValueAccessor touch
286
* @param elSelector - Element selector
287
* @param methodName - CVA method name to call
288
*/
289
function touch(elSelector: DebugNode | DebugNodeSelector, methodName?: string): void;
290
```
291
292
**Usage Examples:**
293
294
```typescript
295
import { ngMocks } from "ng-mocks";
296
297
// Click a button
298
const buttonEl = ngMocks.find('button.submit');
299
ngMocks.click(buttonEl);
300
301
// Click with custom payload
302
ngMocks.click(buttonEl, {
303
ctrlKey: true,
304
clientX: 100,
305
clientY: 200
306
});
307
308
// Trigger keyboard events
309
ngMocks.trigger(inputEl, 'keydown', { key: 'Enter' });
310
ngMocks.trigger(inputEl, 'keydown.control.shift.z');
311
312
// Trigger custom events
313
const customEvent = ngMocks.event('custom-event', {}, { detail: { data: 'test' } });
314
ngMocks.trigger(elementEl, customEvent);
315
316
// Form control interactions
317
ngMocks.change(inputEl, 'new value');
318
ngMocks.touch(inputEl);
319
```
320
321
### Template and Structural Directive Utilities
322
323
Work with ng-container, ng-template, and structural directives.
324
325
```typescript { .api }
326
/**
327
* Finds DebugNodes for ng-container or ng-template elements
328
* @param selector - Component type or CSS selector
329
* @param notFoundValue - Value to return if not found
330
* @returns Found DebugNode or notFoundValue
331
*/
332
function reveal<T>(selector: AnyType<T>): MockedDebugNode<T> | MockedDebugElement<T>;
333
function reveal<T, D>(
334
selector: AnyType<T>,
335
notFoundValue: D
336
): D | MockedDebugNode<T> | MockedDebugElement<T>;
337
function reveal<T = any>(
338
selector: string | [string] | [string, any]
339
): MockedDebugNode<T> | MockedDebugElement<T>;
340
function reveal<T = any, D = undefined>(
341
selector: string | [string] | [string, any],
342
notFoundValue: D
343
): D | MockedDebugNode<T> | MockedDebugElement<T>;
344
345
/**
346
* Finds all DebugNodes for ng-container or ng-template elements
347
* @param selector - Component type or CSS selector
348
* @returns Array of found DebugNodes
349
*/
350
function revealAll<T>(selector: AnyType<T>): Array<MockedDebugNode<T> | MockedDebugElement<T>>;
351
function revealAll<T = any>(
352
selector: string | [string] | [string, any]
353
): Array<MockedDebugNode<T> | MockedDebugElement<T>>;
354
355
/**
356
* Finds TemplateRef instances for rendering
357
* @param elSelector - Element selector
358
* @param selector - Template selector
359
* @param notFoundValue - Value to return if not found
360
* @returns TemplateRef or notFoundValue
361
*/
362
function findTemplateRef<T = any, D = undefined>(
363
elSelector: DebugNodeSelector,
364
selector: string | [string] | [string, any] | AnyType<any>,
365
notFoundValue: D
366
): D | TemplateRef<T>;
367
368
/**
369
* Renders templates or structural directives
370
* @param instance - Component instance
371
* @param template - TemplateRef or DebugNode to render
372
* @param $implicit - Template context $implicit value
373
* @param variables - Template context variables
374
*/
375
function render(
376
instance: object,
377
template: TemplateRef<any> | DebugNode,
378
$implicit?: any,
379
variables?: Record<keyof any, any>
380
): void;
381
382
/**
383
* Hides rendered templates or structural directives
384
* @param instance - Component instance
385
* @param tpl - TemplateRef or DebugNode to hide
386
*/
387
function hide(instance: object, tpl?: TemplateRef<any> | DebugNode): void;
388
```
389
390
**Usage Examples:**
391
392
```typescript
393
import { ngMocks } from "ng-mocks";
394
395
// Find structural directive containers
396
const ngIfEl = ngMocks.reveal(['structural', 'ngIf']);
397
const ngForEls = ngMocks.revealAll(['structural', 'ngFor']);
398
399
// Work with templates
400
const templateRef = ngMocks.findTemplateRef(parentEl, TemplateDirective);
401
const component = ngMocks.get(parentEl, MyComponent);
402
403
// Render template with context
404
ngMocks.render(component, templateRef, 'implicit value', {
405
user: { name: 'John' },
406
index: 0
407
});
408
409
// Hide template
410
ngMocks.hide(component, templateRef);
411
```
412
413
### Utility and Helper Methods
414
415
Additional utility methods for testing support.
416
417
```typescript { .api }
418
/**
419
* Creates stub methods on instances
420
* @param instance - Object to stub
421
* @param name - Property name to stub
422
* @param style - Accessor style ('get' or 'set')
423
* @returns Stubbed function
424
*/
425
function stub<T = MockedFunction, I = any>(
426
instance: I,
427
name: keyof I,
428
style?: 'get' | 'set'
429
): T;
430
431
/**
432
* Applies partial overrides to an instance
433
* @param instance - Object to modify
434
* @param overrides - Properties to override
435
* @returns Modified instance
436
*/
437
function stub<I extends object>(instance: I, overrides: Partial<I>): I;
438
439
/**
440
* Crawls DOM tree correctly handling Angular structures
441
* @param elSelector - Root element selector
442
* @param callback - Function called for each node
443
* @param includeTextNodes - Whether to include text nodes
444
*/
445
function crawl(
446
elSelector: DebugNodeSelector,
447
callback: (
448
node: MockedDebugNode | MockedDebugElement,
449
parent?: MockedDebugNode | MockedDebugElement
450
) => boolean | void,
451
includeTextNodes?: boolean
452
): void;
453
454
/**
455
* Formats HTML for readable output
456
* @param html - Element, fixture, or HTML string
457
* @param outer - Whether to include outer HTML
458
* @returns Formatted HTML string
459
*/
460
function formatHtml(html: any, outer?: boolean): string;
461
462
/**
463
* Formats text content for readable output
464
* @param text - Element, fixture, or text string
465
* @param outer - Whether to include outer text
466
* @returns Formatted text string
467
*/
468
function formatText(text: any, outer?: boolean): string;
469
```
470
471
**Usage Examples:**
472
473
```typescript
474
import { ngMocks } from "ng-mocks";
475
476
// Stub methods
477
const component = ngMocks.get(MyComponent);
478
const saveSpy = ngMocks.stub(component, 'save');
479
const getUserSpy = ngMocks.stub(component, 'user', 'get');
480
481
// Apply overrides
482
ngMocks.stub(component, {
483
isEnabled: true,
484
getData: () => ({ test: 'data' })
485
});
486
487
// Format HTML for assertions
488
const fixture = MockRender(MyComponent);
489
const html = ngMocks.formatHtml(fixture);
490
expect(html).toContain('<my-component>');
491
492
// Crawl DOM structure
493
ngMocks.crawl(fixture.debugElement, (node) => {
494
if (node.componentInstance) {
495
console.log('Found component:', node.componentInstance.constructor.name);
496
}
497
});
498
```