-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
renderer_factory_spec.ts
589 lines (511 loc) Β· 17.3 KB
/
renderer_factory_spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AnimationEvent} from '@angular/animations';
import {
Ι΅AnimationEngine,
Ι΅AnimationRendererFactory,
Ι΅NoopAnimationStyleNormalizer,
} from '@angular/animations/browser';
import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing';
import {CommonModule, DOCUMENT} from '@angular/common';
import {PLATFORM_BROWSER_ID, PLATFORM_SERVER_ID} from '@angular/common/src/platform_id';
import {
Component,
DoCheck,
NgZone,
Renderer2,
RendererFactory2,
RendererStyleFlags2,
RendererType2,
ViewEncapsulation,
} from '@angular/core';
import {RElement} from '@angular/core/src/render3/interfaces/renderer_dom';
import {ngDevModeResetPerfCounters} from '@angular/core/src/util/ng_dev_mode';
import {NoopNgZone} from '@angular/core/src/zone/ng_zone';
import {TestBed} from '@angular/core/testing';
import {EventManager, Ι΅SharedStylesHost} from '@angular/platform-browser';
import {DomRendererFactory2} from '@angular/platform-browser/src/dom/dom_renderer';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('renderer factory lifecycle', () => {
let logs: string[] = [];
let lastCapturedType: RendererType2 | null = null;
@Component({selector: 'some-component', template: `foo`})
class SomeComponent implements DoCheck {
ngOnInit() {
logs.push('some_component create');
}
ngDoCheck() {
logs.push('some_component update');
}
}
@Component({selector: 'some-component-with-error', template: `With error`})
class SomeComponentWhichThrows {
ngOnInit() {
throw new Error('SomeComponentWhichThrows threw');
}
}
@Component({selector: 'lol', template: `<some-component></some-component>`})
class TestComponent implements DoCheck {
ngOnInit() {
logs.push('test_component create');
}
ngDoCheck() {
logs.push('test_component update');
}
}
/** Creates a patched renderer factory that pushes entries to the test log */
function createPatchedRendererFactory(document: any) {
let rendererFactory = getRendererFactory2(document);
const createRender = rendererFactory.createRenderer;
rendererFactory.createRenderer = (hostElement: any, type: RendererType2 | null) => {
logs.push('create');
lastCapturedType = type;
return createRender.apply(rendererFactory, [hostElement, type]);
};
rendererFactory.begin = () => logs.push('begin');
rendererFactory.end = () => logs.push('end');
return rendererFactory;
}
beforeEach(() => {
logs = [];
TestBed.configureTestingModule({
declarations: [SomeComponent, SomeComponentWhichThrows, TestComponent],
providers: [
{
provide: RendererFactory2,
useFactory: (document: any) => createPatchedRendererFactory(document),
deps: [DOCUMENT],
},
],
});
});
it('should work with a component', () => {
const fixture = TestBed.createComponent(SomeComponent);
fixture.componentRef.changeDetectorRef.detectChanges();
expect(logs).toEqual([
'create',
'create',
'begin',
'some_component create',
'some_component update',
'end',
]);
logs = [];
fixture.componentRef.changeDetectorRef.detectChanges();
expect(logs).toEqual(['begin', 'some_component update', 'end']);
});
it('should work with a component which throws', () => {
expect(() => {
const fixture = TestBed.createComponent(SomeComponentWhichThrows);
fixture.componentRef.changeDetectorRef.detectChanges();
}).toThrow();
expect(logs).toEqual(['create', 'create', 'begin', 'end']);
});
it('should pass in the component styles directly into the underlying renderer', () => {
@Component({
standalone: true,
styles: ['.some-css-class { color: red; }'],
template: '...',
encapsulation: ViewEncapsulation.ShadowDom,
})
class StyledComp {}
TestBed.createComponent(StyledComp);
expect(lastCapturedType!.styles).toEqual(['.some-css-class { color: red; }']);
expect(lastCapturedType!.encapsulation).toEqual(ViewEncapsulation.ShadowDom);
});
describe('component animations', () => {
it('should pass in the component styles directly into the underlying renderer', () => {
const animA = {name: 'a'};
const animB = {name: 'b'};
@Component({
standalone: true,
template: '',
animations: [animA, animB],
})
class AnimComp {}
TestBed.createComponent(AnimComp);
const capturedAnimations = lastCapturedType!.data!['animation'];
expect(Array.isArray(capturedAnimations)).toBeTruthy();
expect(capturedAnimations.length).toEqual(2);
expect(capturedAnimations).toContain(animA);
expect(capturedAnimations).toContain(animB);
});
it('should include animations in the renderType data array even if the array is empty', () => {
@Component({
standalone: true,
template: '...',
animations: [],
})
class AnimComp {}
TestBed.createComponent(AnimComp);
const data = lastCapturedType!.data;
expect(data['animation']).toEqual([]);
});
it('should allow [@trigger] bindings to be picked up by the underlying renderer', () => {
@Component({
standalone: true,
template: '<div @fooAnimation></div>',
animations: [],
})
class AnimComp {}
const rendererFactory = new MockRendererFactory(['setProperty']);
TestBed.configureTestingModule({
providers: [
{
provide: RendererFactory2,
useValue: rendererFactory,
deps: [DOCUMENT],
},
],
});
const fixture = TestBed.createComponent(AnimComp);
fixture.detectChanges();
const renderer = rendererFactory.lastRenderer!;
const spy = renderer.spies['setProperty'];
const [_, prop, __] = spy.calls.mostRecent().args;
expect(prop).toEqual('@fooAnimation');
});
});
it('should not invoke renderer destroy method for embedded views', () => {
@Component({
selector: 'comp',
standalone: true,
imports: [CommonModule],
template: `
<div>Root view</div>
<div *ngIf="visible">Child view</div>
`,
})
class Comp {
visible = true;
}
const rendererFactory = new MockRendererFactory(['destroy', 'createElement']);
TestBed.configureTestingModule({
providers: [
{
provide: RendererFactory2,
useValue: rendererFactory,
deps: [DOCUMENT],
},
],
});
const fixture = TestBed.createComponent(Comp);
fixture.detectChanges();
const comp = fixture.componentInstance;
comp!.visible = false;
fixture.detectChanges();
comp!.visible = true;
fixture.detectChanges();
const renderer = rendererFactory.lastRenderer!;
const destroySpy = renderer.spies['destroy'];
const createElementSpy = renderer.spies['createElement'];
// we should never see `destroy` method being called
// in case child views are created/removed.
expect(destroySpy.calls.count()).toBe(0);
// Make sure other methods on the renderer were invoked.
expect(createElementSpy.calls.count() > 0).toBe(true);
});
});
describe('animation renderer factory', () => {
let eventLogs: string[] = [];
let rendererFactory: RendererFactory2 | null = null;
function getAnimationLog(): MockAnimationPlayer[] {
return MockAnimationDriver.log as MockAnimationPlayer[];
}
beforeEach(() => {
eventLogs = [];
rendererFactory = null;
MockAnimationDriver.log = [];
TestBed.configureTestingModule({
declarations: [SomeComponentWithAnimation, SomeComponent],
providers: [
{
provide: RendererFactory2,
useFactory: (d: Document) => (rendererFactory = getAnimationRendererFactory2(d)),
deps: [DOCUMENT],
},
],
});
});
@Component({
selector: 'some-component',
template: `
<div [@myAnimation]="exp"
(@myAnimation.start)="callback($event)"
(@myAnimation.done)="callback($event)">
foo
</div>
`,
animations: [
{
type: 7,
name: 'myAnimation',
definitions: [
{
type: 1,
expr: '* => on',
animation: [
{type: 4, styles: {type: 6, styles: {opacity: 1}, offset: null}, timings: 10},
],
options: null,
},
],
options: {},
},
],
})
class SomeComponentWithAnimation {
exp: string | undefined;
callback(event: AnimationEvent) {
eventLogs.push(`${event.fromState ? event.fromState : event.toState} - ${event.phaseName}`);
}
}
@Component({selector: 'some-component', template: 'foo'})
class SomeComponent {}
it('should work with components without animations', () => {
const fixture = TestBed.createComponent(SomeComponent);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('foo');
});
isBrowser &&
it('should work with animated components', (done) => {
const fixture = TestBed.createComponent(SomeComponentWithAnimation);
fixture.detectChanges();
expect(rendererFactory).toBeTruthy();
expect(fixture.nativeElement.innerHTML).toMatch(
/<div class="ng-tns-c\d+-0 ng-trigger ng-trigger-myAnimation">\s+foo\s+<\/div>/,
);
fixture.componentInstance.exp = 'on';
fixture.detectChanges();
const [player] = getAnimationLog();
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '*'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', 1],
['offset', 1],
]),
]);
player.finish();
rendererFactory!.whenRenderingDone!().then(() => {
expect(eventLogs).toEqual(['void - start', 'void - done', 'on - start', 'on - done']);
done();
});
});
});
function getRendererFactory2(document: Document): RendererFactory2 {
const fakeNgZone: NgZone = new NoopNgZone();
const eventManager = new EventManager([], fakeNgZone);
const appId = 'app-id';
const rendererFactory = new DomRendererFactory2(
eventManager,
new Ι΅SharedStylesHost(document, appId),
appId,
true,
document,
isNode ? PLATFORM_SERVER_ID : PLATFORM_BROWSER_ID,
fakeNgZone,
);
const origCreateRenderer = rendererFactory.createRenderer;
rendererFactory.createRenderer = function (element: any, type: RendererType2 | null) {
const renderer = origCreateRenderer.call(this, element, type);
renderer.destroyNode = () => {};
return renderer;
};
return rendererFactory;
}
function getAnimationRendererFactory2(document: Document): RendererFactory2 {
const fakeNgZone: NgZone = new NoopNgZone();
return new Ι΅AnimationRendererFactory(
getRendererFactory2(document),
new Ι΅AnimationEngine(document, new MockAnimationDriver(), new Ι΅NoopAnimationStyleNormalizer()),
fakeNgZone,
);
}
describe('custom renderer', () => {
@Component({
selector: 'some-component',
template: `<div><span></span></div>`,
})
class SomeComponent {}
/**
* Creates a patched renderer factory that creates elements with a shape different than DOM node
*/
function createPatchedRendererFactory(document: Document) {
let rendererFactory = getRendererFactory2(document);
const origCreateRenderer = rendererFactory.createRenderer;
rendererFactory.createRenderer = function (element: any, type: RendererType2 | null) {
const renderer = origCreateRenderer.call(this, element, type);
renderer.appendChild = () => {};
renderer.createElement = (name: string) => ({
name,
el: document.createElement(name),
});
return renderer;
};
return rendererFactory;
}
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{
provide: RendererFactory2,
useFactory: (document: Document) => createPatchedRendererFactory(document),
deps: [DOCUMENT],
},
],
});
});
it('should not trigger errors', () => {
expect(() => {
const fixture = TestBed.createComponent(SomeComponent);
fixture.detectChanges();
}).not.toThrow();
});
});
describe('Renderer2 destruction hooks', () => {
@Component({
selector: 'some-component',
template: `
<span *ngIf="isContentVisible">A</span>
<span *ngIf="isContentVisible">B</span>
<span *ngIf="isContentVisible">C</span>
`,
})
class SimpleApp {
isContentVisible = true;
}
@Component({
selector: 'basic-comp',
template: 'comp(<ng-content></ng-content>)',
})
class BasicComponent {}
@Component({
selector: 'some-component',
template: `
<basic-comp *ngIf="isContentVisible">A</basic-comp>
<basic-comp *ngIf="isContentVisible">B</basic-comp>
<basic-comp *ngIf="isContentVisible">C</basic-comp>
`,
})
class AppWithComponents {
isContentVisible = true;
}
beforeEach(() => {
// Tests below depend on perf counters when running with Ivy. In order to have
// clean perf counters at the beginning of a test, we reset those here.
ngDevModeResetPerfCounters();
TestBed.configureTestingModule({
declarations: [SimpleApp, AppWithComponents, BasicComponent],
providers: [
{
provide: RendererFactory2,
useFactory: (document: Document) => getRendererFactory2(document),
deps: [DOCUMENT],
},
],
});
});
it('should call renderer.destroyNode for each node destroyed', () => {
const fixture = TestBed.createComponent(SimpleApp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('ABC');
fixture.componentInstance.isContentVisible = false;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('');
expect(ngDevMode!.rendererDestroy).toBe(0);
expect(ngDevMode!.rendererDestroyNode).toBe(3);
});
it('should call renderer.destroy for each component destroyed', () => {
const fixture = TestBed.createComponent(AppWithComponents);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('comp(A)comp(B)comp(C)');
fixture.componentInstance.isContentVisible = false;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('');
expect(ngDevMode!.rendererDestroy).toBe(3);
expect(ngDevMode!.rendererDestroyNode).toBe(3);
});
});
export class MockRendererFactory implements RendererFactory2 {
lastRenderer: any;
private _spyOnMethods: string[];
constructor(spyOnMethods?: string[]) {
this._spyOnMethods = spyOnMethods || [];
}
createRenderer(hostElement: RElement | null, rendererType: RendererType2 | null): Renderer2 {
const renderer = (this.lastRenderer = new MockRenderer(this._spyOnMethods));
return renderer;
}
}
class MockRenderer implements Renderer2 {
public spies: {[methodName: string]: any} = {};
data = {};
destroyNode: ((node: any) => void) | null = null;
constructor(spyOnMethods: string[]) {
spyOnMethods.forEach((methodName) => {
this.spies[methodName] = spyOn(this as any, methodName).and.callThrough();
});
}
destroy(): void {}
createComment(value: string): Comment {
return document.createComment(value);
}
createElement(name: string, namespace?: string | null): Element {
return namespace ? document.createElementNS(namespace, name) : document.createElement(name);
}
createText(value: string): Text {
return document.createTextNode(value);
}
appendChild(parent: RElement, newChild: Node): void {
parent.appendChild(newChild);
}
insertBefore(parent: Node, newChild: Node, refChild: Node | null): void {
parent.insertBefore(newChild, refChild);
}
removeChild(parent: RElement, oldChild: Node): void {
parent.removeChild(oldChild);
}
selectRootElement(selectorOrNode: string | any): RElement {
return typeof selectorOrNode === 'string'
? document.querySelector(selectorOrNode)
: selectorOrNode;
}
parentNode(node: Node): Element | null {
return node.parentNode as Element;
}
nextSibling(node: Node): Node | null {
return node.nextSibling;
}
setAttribute(el: RElement, name: string, value: string, namespace?: string | null): void {
// set all synthetic attributes as properties
if (name[0] === '@') {
this.setProperty(el, name, value);
} else {
el.setAttribute(name, value);
}
}
removeAttribute(el: RElement, name: string, namespace?: string | null): void {}
addClass(el: RElement, name: string): void {}
removeClass(el: RElement, name: string): void {}
setStyle(el: RElement, style: string, value: any, flags?: RendererStyleFlags2): void {}
removeStyle(el: RElement, style: string, flags?: RendererStyleFlags2): void {}
setProperty(el: RElement, name: string, value: any): void {
(el as any)[name] = value;
}
setValue(node: Text, value: string): void {
node.textContent = value;
}
// TODO: Deprecate in favor of addEventListener/removeEventListener
listen(target: Node, eventName: string, callback: (event: any) => boolean | void): () => void {
return () => {};
}
}