Skip to content

test(multiple): clean up DI in tests #30848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {TestBed, inject, waitForAsync} from '@angular/core/testing';
import {TestBed, waitForAsync} from '@angular/core/testing';
import {GuideItems} from './guide-items';

describe('GuideItems', () => {
Expand All @@ -9,10 +9,6 @@ describe('GuideItems', () => {
guideItems = TestBed.inject(GuideItems);
}));

beforeEach(inject([GuideItems], (gi: GuideItems) => {
guideItems = gi;
}));

it('should get a list of all guide items', () => {
expect(guideItems.getAllItems()).toBeDefined();
expect(guideItems.getAllItems().length).toBeGreaterThan(0);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,27 @@
import {HttpClientTestingModule} from '@angular/common/http/testing';
import {inject, TestBed} from '@angular/core/testing';
import {TestBed} from '@angular/core/testing';
import {StyleManager} from './style-manager';

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

beforeEach(() =>
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [StyleManager],
}),
);
});

beforeEach(inject([StyleManager], (sm: StyleManager) => {
styleManager = sm;
}));
styleManager = TestBed.inject(StyleManager);
});

afterEach(() => {
const links = document.head.querySelectorAll('link');
for (const link of Array.prototype.slice.call(links)) {

Array.from(links).forEach(link => {
if (link.className.includes('style-manager-')) {
document.head.removeChild(link);
link.remove();
}
}
});
});

it('should add stylesheet to head', () => {
Expand Down
34 changes: 12 additions & 22 deletions src/cdk/a11y/focus-monitor/focus-monitor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {TAB} from '../../keycodes';
import {Platform} from '../../platform';
import {DOCUMENT} from '@angular/common';
import {Component, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, inject, tick} from '@angular/core/testing';
import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {
createMouseEvent,
Expand Down Expand Up @@ -60,19 +60,17 @@ describe('FocusMonitor', () => {
},
],
});
});

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

buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement;
focusMonitor = fm;
focusMonitor = TestBed.inject(FocusMonitor);

changeHandler = jasmine.createSpy('focus origin change handler');
focusMonitor.monitor(buttonElement).subscribe(changeHandler);
patchElementFocus(buttonElement);
}));
});

it('manually registered element should receive focus classes', fakeAsync(() => {
buttonElement.focus();
Expand Down Expand Up @@ -479,19 +477,17 @@ describe('FocusMonitor with "eventual" detection', () => {
},
],
});
});

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

buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement;
focusMonitor = fm;
focusMonitor = TestBed.inject(FocusMonitor);

changeHandler = jasmine.createSpy('focus origin change handler');
focusMonitor.monitor(buttonElement).subscribe(changeHandler);
patchElementFocus(buttonElement);
}));
});

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

beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
focusMonitor = fm;
beforeEach(() => {
focusMonitor = TestBed.inject(FocusMonitor);
fixture = TestBed.createComponent(
ComplexComponentWithMonitorSubtreeFocusAndMonitorElementFocus,
);
Expand All @@ -724,7 +720,7 @@ describe('cdkMonitorFocus', () => {

patchElementFocus(parentElement);
patchElementFocus(childElement);
}));
});

it('should add keyboard focus classes on both elements when child is focused via keyboard', fakeAsync(() => {
focusMonitor.focusVia(childElement, 'keyboard');
Expand Down Expand Up @@ -828,15 +824,12 @@ describe('FocusMonitor observable stream', () => {
imports: [A11yModule, PlainButton],
providers: [{provide: Platform, useValue: fakePlatform}],
});
});

beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
fixture = TestBed.createComponent(PlainButton);
focusMonitor = fm;
focusMonitor = TestBed.inject(FocusMonitor);
fixture.detectChanges();
buttonElement = fixture.debugElement.nativeElement.querySelector('button');
patchElementFocus(buttonElement);
}));
});

it('should not emit on the server', fakeAsync(() => {
fakePlatform.isBrowser = false;
Expand Down Expand Up @@ -865,16 +858,13 @@ describe('FocusMonitor input label detection', () => {
TestBed.configureTestingModule({
imports: [A11yModule, CheckboxWithLabel],
});
});

beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
fixture = TestBed.createComponent(CheckboxWithLabel);
focusMonitor = fm;
focusMonitor = TestBed.inject(FocusMonitor);
fixture.detectChanges();
inputElement = fixture.nativeElement.querySelector('input');
labelElement = fixture.nativeElement.querySelector('label');
patchElementFocus(inputElement);
}));
});

it('should detect label click focus as `mouse`', fakeAsync(() => {
const spy = jasmine.createSpy('monitor spy');
Expand Down
9 changes: 3 additions & 6 deletions src/cdk/a11y/focus-monitor/focus-monitor.zone.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Platform} from '../../platform';
import {patchElementFocus} from '../../testing/private';
import {Component, NgZone, provideZoneChangeDetection} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, inject, tick} from '@angular/core/testing';
import {ComponentFixture, TestBed, fakeAsync, tick} from '@angular/core/testing';
import {A11yModule} from '../a11y-module';
import {FocusMonitor} from './focus-monitor';

Expand All @@ -17,15 +17,12 @@ describe('FocusMonitor observable stream Zone.js integration', () => {
imports: [A11yModule, PlainButton],
providers: [{provide: Platform, useValue: fakePlatform}, provideZoneChangeDetection()],
});
});

beforeEach(inject([FocusMonitor], (fm: FocusMonitor) => {
fixture = TestBed.createComponent(PlainButton);
focusMonitor = fm;
focusMonitor = TestBed.inject(FocusMonitor);
fixture.detectChanges();
buttonElement = fixture.debugElement.nativeElement.querySelector('button');
patchElementFocus(buttonElement);
}));
});

it('should emit inside the NgZone', fakeAsync(() => {
const spy = jasmine.createSpy('zone spy');
Expand Down
7 changes: 2 additions & 5 deletions src/cdk/drag-drop/drag-drop-registry.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Component} from '@angular/core';
import {fakeAsync, TestBed, ComponentFixture, inject} from '@angular/core/testing';
import {fakeAsync, TestBed, ComponentFixture} from '@angular/core/testing';
import {
createMouseEvent,
dispatchMouseEvent,
Expand All @@ -22,10 +22,7 @@ describe('DragDropRegistry', () => {

fixture = TestBed.createComponent(BlankComponent);
fixture.detectChanges();

inject([DragDropRegistry], (c: DragDropRegistry) => {
registry = c;
})();
registry = TestBed.inject(DragDropRegistry);
}));

it('should be able to start dragging an item', () => {
Expand Down
12 changes: 3 additions & 9 deletions src/cdk/layout/breakpoints-observer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import {LayoutModule} from './layout-module';
import {BreakpointObserver, BreakpointState} from './breakpoints-observer';
import {MediaMatcher} from './media-matcher';
import {fakeAsync, TestBed, inject, flush, tick} from '@angular/core/testing';
import {fakeAsync, TestBed, flush, tick} from '@angular/core/testing';
import {Injectable} from '@angular/core';
import {Subscription} from 'rxjs';
import {skip, take} from 'rxjs/operators';
Expand All @@ -23,16 +23,10 @@ describe('BreakpointObserver', () => {
imports: [LayoutModule],
providers: [{provide: MediaMatcher, useClass: FakeMediaMatcher}],
});
breakpointObserver = TestBed.inject(BreakpointObserver);
mediaMatcher = TestBed.inject(MediaMatcher) as unknown as FakeMediaMatcher;
}));

beforeEach(inject(
[BreakpointObserver, MediaMatcher],
(bm: BreakpointObserver, mm: FakeMediaMatcher) => {
breakpointObserver = bm;
mediaMatcher = mm;
},
));

afterEach(() => {
mediaMatcher.clear();
});
Expand Down
45 changes: 22 additions & 23 deletions src/cdk/layout/media-matcher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,41 +6,40 @@
* found in the LICENSE file at https://angular.dev/license
*/
import {MediaMatcher} from './media-matcher';
import {inject} from '@angular/core/testing';
import {TestBed} from '@angular/core/testing';
import {Platform} from '../platform';

describe('MediaMatcher', () => {
let mediaMatcher: MediaMatcher;
let platform: Platform;

beforeEach(inject([MediaMatcher], (mm: MediaMatcher) => {
mediaMatcher = mm;
}));
beforeEach(() => {
mediaMatcher = TestBed.inject(MediaMatcher);
platform = TestBed.inject(Platform);
});

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

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

expect(getStyleTagByString(width)).toBeFalsy();
mediaMatcher.matchMedia(`(width: ${width})`);
expect(getStyleTagByString(width)).toBeFalsy();
mediaMatcher.matchMedia(`(width: ${width})`);

if (platform.WEBKIT || platform.BLINK) {
expect(getStyleTagByString(width)).toBeTruthy();
} else {
expect(getStyleTagByString(width)).toBeFalsy();
}
if (platform.WEBKIT || platform.BLINK) {
expect(getStyleTagByString(width)).toBeTruthy();
} else {
expect(getStyleTagByString(width)).toBeFalsy();
}

function getStyleTagByString(str: string): HTMLStyleElement | undefined {
return Array.from(document.head!.querySelectorAll('style')).find(tag => {
const rules = tag.sheet ? Array.from((tag.sheet as CSSStyleSheet).cssRules) : [];
return !!rules.find(rule => rule.cssText.includes(str));
});
}
},
));
function getStyleTagByString(str: string): HTMLStyleElement | undefined {
return Array.from(document.head!.querySelectorAll('style')).find(tag => {
const rules = tag.sheet ? Array.from((tag.sheet as CSSStyleSheet).cssRules) : [];
return !!rules.find(rule => rule.cssText.includes(str));
});
}
});
});
54 changes: 22 additions & 32 deletions src/cdk/observers/observe-content.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import {Component, ElementRef, ViewChild} from '@angular/core';
import {
ComponentFixture,
TestBed,
fakeAsync,
inject,
tick,
waitForAsync,
} from '@angular/core/testing';
import {ComponentFixture, TestBed, fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {ContentObserver, MutationObserverFactory, ObserversModule} from './observe-content';

describe('Observe content directive', () => {
Expand Down Expand Up @@ -147,10 +140,8 @@ describe('ContentObserver injectable', () => {
},
],
});
}));

beforeEach(inject([ContentObserver], (co: ContentObserver) => {
contentObserver = co;
contentObserver = TestBed.inject(ContentObserver);
}));

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

it('should only create one MutationObserver when observing the same element twice', fakeAsync(
inject([MutationObserverFactory], (mof: MutationObserverFactory) => {
const spy = jasmine.createSpy('content observer');
spyOn(mof, 'create').and.callThrough();
const fixture = TestBed.createComponent(UnobservedComponentWithTextContent);
fixture.detectChanges();
it('should only create one MutationObserver when observing the same element twice', fakeAsync(() => {
const observerFactory = TestBed.inject(MutationObserverFactory);
const spy = jasmine.createSpy('content observer');
spyOn(observerFactory, 'create').and.callThrough();
const fixture = TestBed.createComponent(UnobservedComponentWithTextContent);
fixture.detectChanges();

const sub1 = contentObserver
.observe(fixture.componentInstance.contentEl)
.subscribe(() => spy());
contentObserver.observe(fixture.componentInstance.contentEl).subscribe(() => spy());
const sub1 = contentObserver
.observe(fixture.componentInstance.contentEl)
.subscribe(() => spy());
contentObserver.observe(fixture.componentInstance.contentEl).subscribe(() => spy());

expect(mof.create).toHaveBeenCalledTimes(1);
expect(observerFactory.create).toHaveBeenCalledTimes(1);

fixture.componentInstance.text = 'text';
invokeCallbacks([{type: 'fake'}]);
fixture.componentInstance.text = 'text';
invokeCallbacks([{type: 'fake'}]);

expect(spy).toHaveBeenCalledTimes(2);
expect(spy).toHaveBeenCalledTimes(2);

spy.calls.reset();
sub1.unsubscribe();
fixture.componentInstance.text = 'text text';
invokeCallbacks([{type: 'fake'}]);
spy.calls.reset();
sub1.unsubscribe();
fixture.componentInstance.text = 'text text';
invokeCallbacks([{type: 'fake'}]);

expect(spy).toHaveBeenCalledTimes(1);
}),
));
expect(spy).toHaveBeenCalledTimes(1);
}));
});

describe('real behavior', () => {
Expand Down
Loading
Loading