Skip to content

Commit 4e0ea8e

Browse files
authored
test(multiple): clean up DI in tests (#30848)
We have some tests that are using the `inject` function from `@angular/core/testing` to inject services. This hasn't been the standard for a while and leads to a lot of boilerplate. These changes switch to using `TestBed.inject` and clean up the existing code.
1 parent 5dcbba7 commit 4e0ea8e

33 files changed

+310
-490
lines changed

Diff for: material.angular.io/src/app/shared/guide-items/guide-items.spec.ts

+1-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {TestBed, inject, waitForAsync} from '@angular/core/testing';
1+
import {TestBed, waitForAsync} from '@angular/core/testing';
22
import {GuideItems} from './guide-items';
33

44
describe('GuideItems', () => {
@@ -9,10 +9,6 @@ describe('GuideItems', () => {
99
guideItems = TestBed.inject(GuideItems);
1010
}));
1111

12-
beforeEach(inject([GuideItems], (gi: GuideItems) => {
13-
guideItems = gi;
14-
}));
15-
1612
it('should get a list of all guide items', () => {
1713
expect(guideItems.getAllItems()).toBeDefined();
1814
expect(guideItems.getAllItems().length).toBeGreaterThan(0);

Diff for: material.angular.io/src/app/shared/style-manager/style-manager.spec.ts

+9-10
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,27 @@
11
import {HttpClientTestingModule} from '@angular/common/http/testing';
2-
import {inject, TestBed} from '@angular/core/testing';
2+
import {TestBed} from '@angular/core/testing';
33
import {StyleManager} from './style-manager';
44

55
describe('StyleManager', () => {
66
let styleManager: StyleManager;
77

8-
beforeEach(() =>
8+
beforeEach(() => {
99
TestBed.configureTestingModule({
1010
imports: [HttpClientTestingModule],
1111
providers: [StyleManager],
12-
}),
13-
);
12+
});
1413

15-
beforeEach(inject([StyleManager], (sm: StyleManager) => {
16-
styleManager = sm;
17-
}));
14+
styleManager = TestBed.inject(StyleManager);
15+
});
1816

1917
afterEach(() => {
2018
const links = document.head.querySelectorAll('link');
21-
for (const link of Array.prototype.slice.call(links)) {
19+
20+
Array.from(links).forEach(link => {
2221
if (link.className.includes('style-manager-')) {
23-
document.head.removeChild(link);
22+
link.remove();
2423
}
25-
}
24+
});
2625
});
2726

2827
it('should add stylesheet to head', () => {

Diff for: src/cdk/a11y/focus-monitor/focus-monitor.spec.ts

+12-22
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import {TAB} from '../../keycodes';
22
import {Platform} from '../../platform';
33
import {DOCUMENT} from '@angular/common';
44
import {Component, ViewChild} from '@angular/core';
5-
import {ComponentFixture, TestBed, fakeAsync, flush, inject, tick} from '@angular/core/testing';
5+
import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing';
66
import {By} from '@angular/platform-browser';
77
import {
88
createMouseEvent,
@@ -60,19 +60,17 @@ describe('FocusMonitor', () => {
6060
},
6161
],
6262
});
63-
});
6463

65-
beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
6664
fixture = TestBed.createComponent(PlainButton);
6765
fixture.detectChanges();
6866

6967
buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement;
70-
focusMonitor = fm;
68+
focusMonitor = TestBed.inject(FocusMonitor);
7169

7270
changeHandler = jasmine.createSpy('focus origin change handler');
7371
focusMonitor.monitor(buttonElement).subscribe(changeHandler);
7472
patchElementFocus(buttonElement);
75-
}));
73+
});
7674

7775
it('manually registered element should receive focus classes', fakeAsync(() => {
7876
buttonElement.focus();
@@ -479,19 +477,17 @@ describe('FocusMonitor with "eventual" detection', () => {
479477
},
480478
],
481479
});
482-
});
483480

484-
beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
485481
fixture = TestBed.createComponent(PlainButton);
486482
fixture.detectChanges();
487483

488484
buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement;
489-
focusMonitor = fm;
485+
focusMonitor = TestBed.inject(FocusMonitor);
490486

491487
changeHandler = jasmine.createSpy('focus origin change handler');
492488
focusMonitor.monitor(buttonElement).subscribe(changeHandler);
493489
patchElementFocus(buttonElement);
494-
}));
490+
});
495491

496492
it('should not clear the focus origin, even after a few seconds', fakeAsync(() => {
497493
dispatchKeyboardEvent(document, 'keydown', TAB);
@@ -712,8 +708,8 @@ describe('cdkMonitorFocus', () => {
712708
let childElement: HTMLElement;
713709
let focusMonitor: FocusMonitor;
714710

715-
beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
716-
focusMonitor = fm;
711+
beforeEach(() => {
712+
focusMonitor = TestBed.inject(FocusMonitor);
717713
fixture = TestBed.createComponent(
718714
ComplexComponentWithMonitorSubtreeFocusAndMonitorElementFocus,
719715
);
@@ -724,7 +720,7 @@ describe('cdkMonitorFocus', () => {
724720

725721
patchElementFocus(parentElement);
726722
patchElementFocus(childElement);
727-
}));
723+
});
728724

729725
it('should add keyboard focus classes on both elements when child is focused via keyboard', fakeAsync(() => {
730726
focusMonitor.focusVia(childElement, 'keyboard');
@@ -828,15 +824,12 @@ describe('FocusMonitor observable stream', () => {
828824
imports: [A11yModule, PlainButton],
829825
providers: [{provide: Platform, useValue: fakePlatform}],
830826
});
831-
});
832-
833-
beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
834827
fixture = TestBed.createComponent(PlainButton);
835-
focusMonitor = fm;
828+
focusMonitor = TestBed.inject(FocusMonitor);
836829
fixture.detectChanges();
837830
buttonElement = fixture.debugElement.nativeElement.querySelector('button');
838831
patchElementFocus(buttonElement);
839-
}));
832+
});
840833

841834
it('should not emit on the server', fakeAsync(() => {
842835
fakePlatform.isBrowser = false;
@@ -865,16 +858,13 @@ describe('FocusMonitor input label detection', () => {
865858
TestBed.configureTestingModule({
866859
imports: [A11yModule, CheckboxWithLabel],
867860
});
868-
});
869-
870-
beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
871861
fixture = TestBed.createComponent(CheckboxWithLabel);
872-
focusMonitor = fm;
862+
focusMonitor = TestBed.inject(FocusMonitor);
873863
fixture.detectChanges();
874864
inputElement = fixture.nativeElement.querySelector('input');
875865
labelElement = fixture.nativeElement.querySelector('label');
876866
patchElementFocus(inputElement);
877-
}));
867+
});
878868

879869
it('should detect label click focus as `mouse`', fakeAsync(() => {
880870
const spy = jasmine.createSpy('monitor spy');

Diff for: src/cdk/a11y/focus-monitor/focus-monitor.zone.spec.ts

+3-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import {Platform} from '../../platform';
22
import {patchElementFocus} from '../../testing/private';
33
import {Component, NgZone, provideZoneChangeDetection} from '@angular/core';
4-
import {ComponentFixture, TestBed, fakeAsync, inject, tick} from '@angular/core/testing';
4+
import {ComponentFixture, TestBed, fakeAsync, tick} from '@angular/core/testing';
55
import {A11yModule} from '../a11y-module';
66
import {FocusMonitor} from './focus-monitor';
77

@@ -17,15 +17,12 @@ describe('FocusMonitor observable stream Zone.js integration', () => {
1717
imports: [A11yModule, PlainButton],
1818
providers: [{provide: Platform, useValue: fakePlatform}, provideZoneChangeDetection()],
1919
});
20-
});
21-
22-
beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
2320
fixture = TestBed.createComponent(PlainButton);
24-
focusMonitor = fm;
21+
focusMonitor = TestBed.inject(FocusMonitor);
2522
fixture.detectChanges();
2623
buttonElement = fixture.debugElement.nativeElement.querySelector('button');
2724
patchElementFocus(buttonElement);
28-
}));
25+
});
2926

3027
it('should emit inside the NgZone', fakeAsync(() => {
3128
const spy = jasmine.createSpy('zone spy');

Diff for: src/cdk/drag-drop/drag-drop-registry.spec.ts

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {Component} from '@angular/core';
2-
import {fakeAsync, TestBed, ComponentFixture, inject} from '@angular/core/testing';
2+
import {fakeAsync, TestBed, ComponentFixture} from '@angular/core/testing';
33
import {
44
createMouseEvent,
55
dispatchMouseEvent,
@@ -22,10 +22,7 @@ describe('DragDropRegistry', () => {
2222

2323
fixture = TestBed.createComponent(BlankComponent);
2424
fixture.detectChanges();
25-
26-
inject([DragDropRegistry], (c: DragDropRegistry) => {
27-
registry = c;
28-
})();
25+
registry = TestBed.inject(DragDropRegistry);
2926
}));
3027

3128
it('should be able to start dragging an item', () => {

Diff for: src/cdk/layout/breakpoints-observer.spec.ts

+3-9
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import {LayoutModule} from './layout-module';
1010
import {BreakpointObserver, BreakpointState} from './breakpoints-observer';
1111
import {MediaMatcher} from './media-matcher';
12-
import {fakeAsync, TestBed, inject, flush, tick} from '@angular/core/testing';
12+
import {fakeAsync, TestBed, flush, tick} from '@angular/core/testing';
1313
import {Injectable} from '@angular/core';
1414
import {Subscription} from 'rxjs';
1515
import {skip, take} from 'rxjs/operators';
@@ -23,16 +23,10 @@ describe('BreakpointObserver', () => {
2323
imports: [LayoutModule],
2424
providers: [{provide: MediaMatcher, useClass: FakeMediaMatcher}],
2525
});
26+
breakpointObserver = TestBed.inject(BreakpointObserver);
27+
mediaMatcher = TestBed.inject(MediaMatcher) as unknown as FakeMediaMatcher;
2628
}));
2729

28-
beforeEach(inject(
29-
[BreakpointObserver, MediaMatcher],
30-
(bm: BreakpointObserver, mm: FakeMediaMatcher) => {
31-
breakpointObserver = bm;
32-
mediaMatcher = mm;
33-
},
34-
));
35-
3630
afterEach(() => {
3731
mediaMatcher.clear();
3832
});

Diff for: src/cdk/layout/media-matcher.spec.ts

+22-23
Original file line numberDiff line numberDiff line change
@@ -6,41 +6,40 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88
import {MediaMatcher} from './media-matcher';
9-
import {inject} from '@angular/core/testing';
9+
import {TestBed} from '@angular/core/testing';
1010
import {Platform} from '../platform';
1111

1212
describe('MediaMatcher', () => {
1313
let mediaMatcher: MediaMatcher;
14+
let platform: Platform;
1415

15-
beforeEach(inject([MediaMatcher], (mm: MediaMatcher) => {
16-
mediaMatcher = mm;
17-
}));
16+
beforeEach(() => {
17+
mediaMatcher = TestBed.inject(MediaMatcher);
18+
platform = TestBed.inject(Platform);
19+
});
1820

1921
it('correctly returns a MediaQueryList to check for matches', () => {
2022
expect(mediaMatcher.matchMedia('(min-width: 1px)').matches).toBeTruthy();
2123
expect(mediaMatcher.matchMedia('(max-width: 1px)').matches).toBeFalsy();
2224
});
2325

24-
it('should add CSS rules for provided queries when the platform is webkit or blink', inject(
25-
[Platform],
26-
(platform: Platform) => {
27-
const width = '123456px';
26+
it('should add CSS rules for provided queries when the platform is webkit or blink', () => {
27+
const width = '123456px';
2828

29-
expect(getStyleTagByString(width)).toBeFalsy();
30-
mediaMatcher.matchMedia(`(width: ${width})`);
29+
expect(getStyleTagByString(width)).toBeFalsy();
30+
mediaMatcher.matchMedia(`(width: ${width})`);
3131

32-
if (platform.WEBKIT || platform.BLINK) {
33-
expect(getStyleTagByString(width)).toBeTruthy();
34-
} else {
35-
expect(getStyleTagByString(width)).toBeFalsy();
36-
}
32+
if (platform.WEBKIT || platform.BLINK) {
33+
expect(getStyleTagByString(width)).toBeTruthy();
34+
} else {
35+
expect(getStyleTagByString(width)).toBeFalsy();
36+
}
3737

38-
function getStyleTagByString(str: string): HTMLStyleElement | undefined {
39-
return Array.from(document.head!.querySelectorAll('style')).find(tag => {
40-
const rules = tag.sheet ? Array.from((tag.sheet as CSSStyleSheet).cssRules) : [];
41-
return !!rules.find(rule => rule.cssText.includes(str));
42-
});
43-
}
44-
},
45-
));
38+
function getStyleTagByString(str: string): HTMLStyleElement | undefined {
39+
return Array.from(document.head!.querySelectorAll('style')).find(tag => {
40+
const rules = tag.sheet ? Array.from((tag.sheet as CSSStyleSheet).cssRules) : [];
41+
return !!rules.find(rule => rule.cssText.includes(str));
42+
});
43+
}
44+
});
4645
});

Diff for: src/cdk/observers/observe-content.spec.ts

+22-32
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,5 @@
11
import {Component, ElementRef, ViewChild} from '@angular/core';
2-
import {
3-
ComponentFixture,
4-
TestBed,
5-
fakeAsync,
6-
inject,
7-
tick,
8-
waitForAsync,
9-
} from '@angular/core/testing';
2+
import {ComponentFixture, TestBed, fakeAsync, tick, waitForAsync} from '@angular/core/testing';
103
import {ContentObserver, MutationObserverFactory, ObserversModule} from './observe-content';
114

125
describe('Observe content directive', () => {
@@ -147,10 +140,8 @@ describe('ContentObserver injectable', () => {
147140
},
148141
],
149142
});
150-
}));
151143

152-
beforeEach(inject([ContentObserver], (co: ContentObserver) => {
153-
contentObserver = co;
144+
contentObserver = TestBed.inject(ContentObserver);
154145
}));
155146

156147
it('should trigger the callback when the content of the element changes', fakeAsync(() => {
@@ -168,33 +159,32 @@ describe('ContentObserver injectable', () => {
168159
expect(spy).toHaveBeenCalled();
169160
}));
170161

171-
it('should only create one MutationObserver when observing the same element twice', fakeAsync(
172-
inject([MutationObserverFactory], (mof: MutationObserverFactory) => {
173-
const spy = jasmine.createSpy('content observer');
174-
spyOn(mof, 'create').and.callThrough();
175-
const fixture = TestBed.createComponent(UnobservedComponentWithTextContent);
176-
fixture.detectChanges();
162+
it('should only create one MutationObserver when observing the same element twice', fakeAsync(() => {
163+
const observerFactory = TestBed.inject(MutationObserverFactory);
164+
const spy = jasmine.createSpy('content observer');
165+
spyOn(observerFactory, 'create').and.callThrough();
166+
const fixture = TestBed.createComponent(UnobservedComponentWithTextContent);
167+
fixture.detectChanges();
177168

178-
const sub1 = contentObserver
179-
.observe(fixture.componentInstance.contentEl)
180-
.subscribe(() => spy());
181-
contentObserver.observe(fixture.componentInstance.contentEl).subscribe(() => spy());
169+
const sub1 = contentObserver
170+
.observe(fixture.componentInstance.contentEl)
171+
.subscribe(() => spy());
172+
contentObserver.observe(fixture.componentInstance.contentEl).subscribe(() => spy());
182173

183-
expect(mof.create).toHaveBeenCalledTimes(1);
174+
expect(observerFactory.create).toHaveBeenCalledTimes(1);
184175

185-
fixture.componentInstance.text = 'text';
186-
invokeCallbacks([{type: 'fake'}]);
176+
fixture.componentInstance.text = 'text';
177+
invokeCallbacks([{type: 'fake'}]);
187178

188-
expect(spy).toHaveBeenCalledTimes(2);
179+
expect(spy).toHaveBeenCalledTimes(2);
189180

190-
spy.calls.reset();
191-
sub1.unsubscribe();
192-
fixture.componentInstance.text = 'text text';
193-
invokeCallbacks([{type: 'fake'}]);
181+
spy.calls.reset();
182+
sub1.unsubscribe();
183+
fixture.componentInstance.text = 'text text';
184+
invokeCallbacks([{type: 'fake'}]);
194185

195-
expect(spy).toHaveBeenCalledTimes(1);
196-
}),
197-
));
186+
expect(spy).toHaveBeenCalledTimes(1);
187+
}));
198188
});
199189

200190
describe('real behavior', () => {

0 commit comments

Comments
 (0)