build: update jasmine dependencies to v7

Updates Jasmine dependencies across the workspace to v7, retaining Jasmine 6
in packages/zone.js for its internal tests.

To support Jasmine 7 without relying on zone.js/plugins/jasmine-patch (which
cannot patch Jasmine 7 due to frozen environment properties and internal API
changes), unit tests across packages have been migrated off fakeAsync and
waitForAsync to standard asynchronous APIs (whenStable, useAutoTick, timeout,
and jasmine.clock).
This commit is contained in:
Andrew Scott
2026-10-21 09:07:29 -07:00
committed by Leon Senft
parent a59ad76b08
commit e8a7e49e6b
39 changed files with 2961 additions and 2780 deletions
+2 -2
View File
@@ -51,7 +51,7 @@
"@shikijs/vscode-textmate": "^10.0.2",
"@stackblitz/sdk": "1.11.1",
"@types/dom-navigation": "1.0.7",
"@types/jasmine": "6.0.0",
"@types/jasmine": "7.0.0",
"@types/jsdom": "30.0.0",
"@types/node": "24.19.2",
"@typescript/vfs": "1.6.5",
@@ -72,7 +72,7 @@
"hast-util-to-html": "^9.0.5",
"hast-util-whitespace": "^3.0.0",
"html-void-elements": "^3.0.0",
"jasmine-core": "6.3.0",
"jasmine-core": "7.0.2",
"jsdom": "30.1.2",
"karma-chrome-launcher": "3.2.0",
"karma-coverage": "2.2.1",
@@ -31,7 +31,7 @@ const ITEMS: HistoryItem[] = [
},
].map((i) => ({...i, url: '', createdAt: 0, isFavorite: false}));
describe('SearchHistory', async () => {
describe('SearchHistory', () => {
let service: SearchHistory;
let storage: Storage;
@@ -21,7 +21,7 @@ describe('ApiLabel', () => {
expect(result).toBe('C');
});
it(`should return short label when labelType equals short`, () => {
it(`should return full label when labelType equals full`, () => {
const result = pipe.transform(ApiItemType.CLASS, 'full');
expect(result).toBe('Class');
});
+1 -1
View File
@@ -13,7 +13,7 @@
"@angular/platform-browser": "workspace:*",
"@angular/router": "workspace:*",
"@angular/upgrade": "workspace:*",
"@types/jasmine": "6.0.0",
"@types/jasmine": "7.0.0",
"@types/jasminewd2": "2.0.13",
"@types/node": "24.19.2",
"@types/selenium-webdriver": "3.0.7",
+1 -1
View File
@@ -160,7 +160,7 @@
"vscode-uri": "^3.1.0"
},
"devDependencies": {
"@types/jasmine": "^6.0.0",
"@types/jasmine": "^7.0.0",
"@types/node": "^20.14.8",
"@types/vscode": "^1.125.0",
"@vscode/test-electron": "^3.1.0",
+3 -3
View File
@@ -88,7 +88,7 @@
"@types/angular": "^1.6.47",
"@types/chrome": "^0.3.0",
"@types/dom-navigation": "^1.0.5",
"@types/jasmine": "^6.0.0",
"@types/jasmine": "^7.0.0",
"@types/jasminewd2": "^2.0.8",
"@types/node": "^20.14.8",
"@types/selenium-webdriver": "3.0.7",
@@ -107,8 +107,8 @@
"domino": "https://github.com/angular/domino.git#1929b1ef5aee03234de322c5bbd955ba653d8727",
"esbuild": "0.28.2",
"http-server": "^14.0.0",
"jasmine": "6.3.0",
"jasmine-core": "6.3.0",
"jasmine": "7.0.0",
"jasmine-core": "7.0.2",
"jasmine-reporters": "^2.5.2",
"karma": "~6.4.0",
"karma-chrome-launcher": "^3.1.0",
@@ -5,26 +5,25 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {fakeAsync} from '@angular/core/testing';
import {NoopAnimationPlayer} from '../src/animations';
import {AnimationGroupPlayer} from '../src/players/animation_group_player';
describe('AnimationGroupPlayer', () => {
it('should getPosition of an empty group', fakeAsync(() => {
it('should getPosition of an empty group', () => {
const players: NoopAnimationPlayer[] = [];
const groupPlayer = new AnimationGroupPlayer(players);
expect(groupPlayer.getPosition()).toBe(0);
}));
});
it('should getPosition of a single player in a group', fakeAsync(() => {
it('should getPosition of a single player in a group', () => {
const player = new NoopAnimationPlayer(5, 5);
player.setPosition(0.2);
const players = [player];
const groupPlayer = new AnimationGroupPlayer(players);
expect(groupPlayer.getPosition()).toBe(0.2);
}));
});
it('should getPosition based on the longest player in the group', fakeAsync(() => {
it('should getPosition based on the longest player in the group', () => {
const longestPlayer = new NoopAnimationPlayer(5, 5);
longestPlayer.setPosition(0.2);
const players = [
@@ -36,5 +35,5 @@ describe('AnimationGroupPlayer', () => {
];
const groupPlayer = new AnimationGroupPlayer(players);
expect(groupPlayer.getPosition()).toBe(0.2);
}));
});
});
@@ -5,27 +5,24 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {fakeAsync} from '@angular/core/testing';
import {flushMicrotasks} from '../../core/testing/src/fake_async';
import {NoopAnimationPlayer} from '../src/players/animation_player';
describe('NoopAnimationPlayer', () => {
it('should finish after the next microtask once started', fakeAsync(() => {
it('should finish after the next microtask once started', async () => {
const log: string[] = [];
const player = new NoopAnimationPlayer();
player.onStart(() => log.push('started'));
player.onDone(() => log.push('done'));
flushMicrotasks();
await Promise.resolve();
expect(log).toEqual([]);
player.play();
expect(log).toEqual(['started']);
flushMicrotasks();
await Promise.resolve();
expect(log).toEqual(['started', 'done']);
}));
});
it('should fire all callbacks when destroyed', () => {
const log: string[] = [];
@@ -40,13 +37,13 @@ describe('NoopAnimationPlayer', () => {
expect(log).toEqual(['started', 'done', 'destroy']);
});
it('should fire start/done callbacks manually when called directly', fakeAsync(() => {
it('should fire start/done callbacks manually when called directly', async () => {
const log: string[] = [];
const player = new NoopAnimationPlayer();
player.onStart(() => log.push('started'));
player.onDone(() => log.push('done'));
flushMicrotasks();
await Promise.resolve();
(player as any).triggerCallback('start');
expect(log).toEqual(['started']);
@@ -60,11 +57,11 @@ describe('NoopAnimationPlayer', () => {
player.finish();
expect(log).toEqual(['started', 'done']);
flushMicrotasks();
await Promise.resolve();
expect(log).toEqual(['started', 'done']);
}));
});
it('should fire off start callbacks before triggering the finish callback', fakeAsync(() => {
it('should fire off start callbacks before triggering the finish callback', async () => {
const log: string[] = [];
const player = new NoopAnimationPlayer();
@@ -77,7 +74,7 @@ describe('NoopAnimationPlayer', () => {
player.play();
expect(log).toEqual([]);
flushMicrotasks();
await Promise.resolve();
expect(log).toEqual(['started', 'done']);
}));
});
});
@@ -14,7 +14,7 @@ import {
RendererFactory2,
ViewChild,
} from '@angular/core';
import {fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing';
import {TestBed} from '@angular/core/testing';
import {ɵDomRendererFactory2 as DomRendererFactory2} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {ɵAsyncAnimationRendererFactory as AsyncAnimationRendererFactory} from '@angular/platform-browser/animations/async';
@@ -62,7 +62,7 @@ describe('BrowserAnimationBuilder', () => {
expect(cmp.builder instanceof BrowserAnimationBuilder).toBeTruthy();
});
it("should listen on start and done on the animation builder's player after it has been reset", fakeAsync(() => {
it("should listen on start and done on the animation builder's player after it has been reset", async () => {
@Component({
template: '...',
})
@@ -83,7 +83,7 @@ describe('BrowserAnimationBuilder', () => {
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
await fixture.whenStable();
const player = cmp.build();
@@ -94,42 +94,42 @@ describe('BrowserAnimationBuilder', () => {
player.onDone(() => finishedCount++);
player.init();
flushMicrotasks();
await Promise.resolve();
expect(startedCount).toEqual(0);
expect(finishedCount).toEqual(0);
player.play();
flushMicrotasks();
await Promise.resolve();
expect(startedCount).toEqual(1);
expect(finishedCount).toEqual(0);
player.finish();
flushMicrotasks();
await Promise.resolve();
expect(startedCount).toEqual(1);
expect(finishedCount).toEqual(1);
player.play();
player.finish();
flushMicrotasks();
await Promise.resolve();
expect(startedCount).toEqual(1);
expect(finishedCount).toEqual(1);
[0, 1, 2, 3].forEach((i) => {
for (const i of [0, 1, 2, 3]) {
player.reset();
player.play();
flushMicrotasks();
await Promise.resolve();
expect(startedCount).toEqual(i + 2);
expect(finishedCount).toEqual(i + 1);
player.finish();
flushMicrotasks();
await Promise.resolve();
expect(startedCount).toEqual(i + 2);
expect(finishedCount).toEqual(i + 2);
});
}));
}
});
it("should listen on start and done on the animation builder's player", fakeAsync(() => {
it("should listen on start and done on the animation builder's player", async () => {
@Component({
template: '...',
})
@@ -150,7 +150,7 @@ describe('BrowserAnimationBuilder', () => {
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
await fixture.whenStable();
const player = cmp.build();
@@ -164,31 +164,31 @@ describe('BrowserAnimationBuilder', () => {
player.onDestroy(() => (destroyed = true));
player.init();
flushMicrotasks();
await Promise.resolve();
expect(started).toBeFalsy();
expect(finished).toBeFalsy();
expect(destroyed).toBeFalsy();
player.play();
flushMicrotasks();
await Promise.resolve();
expect(started).toBeTruthy();
expect(finished).toBeFalsy();
expect(destroyed).toBeFalsy();
player.finish();
flushMicrotasks();
await Promise.resolve();
expect(started).toBeTruthy();
expect(finished).toBeTruthy();
expect(destroyed).toBeFalsy();
player.destroy();
flushMicrotasks();
await Promise.resolve();
expect(started).toBeTruthy();
expect(finished).toBeTruthy();
expect(destroyed).toBeTruthy();
}));
});
it('should update `hasStarted()` on `play()` and `reset()`', fakeAsync(() => {
it('should update `hasStarted()` on `play()` and `reset()`', async () => {
@Component({
template: '...',
})
@@ -209,21 +209,21 @@ describe('BrowserAnimationBuilder', () => {
const fixture = TestBed.createComponent(CmpAnother);
const cmp = fixture.componentInstance;
fixture.detectChanges();
await fixture.whenStable();
const player = cmp.build();
expect(player.hasStarted()).toBeFalsy();
flushMicrotasks();
await Promise.resolve();
player.play();
flushMicrotasks();
await Promise.resolve();
expect(player.hasStarted()).toBeTruthy();
player.reset();
flushMicrotasks();
await Promise.resolve();
expect(player.hasStarted()).toBeFalsy();
}));
});
describe('without Animations enabled', () => {
beforeEach(() => {
@@ -19,7 +19,7 @@ import {toObservable} from '../src';
import {ComponentFixture, TestBed} from '../../testing';
import {take, toArray} from 'rxjs/operators';
describe('toObservable()', async () => {
describe('toObservable()', () => {
let fixture!: ComponentFixture<unknown>;
let injector!: EnvironmentInjector;
+1 -1
View File
@@ -772,7 +772,7 @@ describe('pipe', () => {
expect(fixture.nativeElement.textContent).toBe('anything');
});
describe('pure pipe error handling with multiple arguments', async () => {
describe('pure pipe error handling with multiple arguments', () => {
const args: string[] = new Array(10).fill(':0');
for (let numberOfPipeArgs = 0; numberOfPipeArgs < args.length; numberOfPipeArgs++) {
it(`should not invoke ${numberOfPipeArgs} argument pure pipe second time if it throws unless input changes`, () => {
@@ -54,6 +54,8 @@ import {RuntimeError, RuntimeErrorCode} from '../src/errors';
import {scheduleCallbackWithRafRace} from '../src/util/callback_scheduler';
import {global} from '../src/util/global';
const {withProxyZone} = (Zone as any)[Zone.__symbol__('fakeAsyncTest')];
function isStable(injector = TestBed.inject(EnvironmentInjector)): boolean {
return toSignal(injector.get(ApplicationRef).isStable, {requireSync: true, injector})();
}
@@ -709,46 +711,56 @@ describe('Angular with zoneless enabled', () => {
(Zone.root as any)._zoneDelegate.handleError = previousHandle;
});
it('runs inside fakeAsync zone', fakeAsync(() => {
let didRun = false;
@Component({template: ''})
class App {
ngOnInit() {
didRun = true;
}
}
it(
'runs inside fakeAsync zone',
withProxyZone(
fakeAsync(() => {
let didRun = false;
@Component({template: ''})
class App {
ngOnInit() {
didRun = true;
}
}
TestBed.createComponent(App);
expect(didRun).toBe(false);
tick();
expect(didRun).toBe(true);
TestBed.createComponent(App);
expect(didRun).toBe(false);
tick();
expect(didRun).toBe(true);
didRun = false;
TestBed.createComponent(App);
expect(didRun).toBe(false);
flush();
expect(didRun).toBe(true);
}));
didRun = false;
TestBed.createComponent(App);
expect(didRun).toBe(false);
flush();
expect(didRun).toBe(true);
}),
),
);
it('can run inside fakeAsync zone', fakeAsync(() => {
let didRun = false;
@Component({template: ''})
class App {
ngDoCheck() {
didRun = true;
}
}
it(
'can run inside fakeAsync zone',
withProxyZone(
fakeAsync(() => {
let didRun = false;
@Component({template: ''})
class App {
ngDoCheck() {
didRun = true;
}
}
// create component runs inside the zone and triggers CD as a result
const fixture = TestBed.createComponent(App);
didRun = false;
// create component runs inside the zone and triggers CD as a result
const fixture = TestBed.createComponent(App);
didRun = false;
// schedules change detection
fixture.debugElement.injector.get(ChangeDetectorRef).markForCheck();
expect(didRun).toBe(false);
tick();
expect(didRun).toBe(true);
}));
// schedules change detection
fixture.debugElement.injector.get(ChangeDetectorRef).markForCheck();
expect(didRun).toBe(false);
tick();
expect(didRun).toBe(true);
}),
),
);
});
describe('Angular with scheduler and ZoneJS', () => {
@@ -959,28 +971,33 @@ describe('Angular with scheduler and ZoneJS', () => {
expect(ticks).toBe(1);
});
it('can run inside fakeAsync zone', fakeAsync(() => {
TestBed.configureTestingModule({
providers: [provideZoneChangeDetection({scheduleInRootZone: false} as any)],
});
let didRun = false;
@Component({template: ''})
class App {
ngDoCheck() {
didRun = true;
}
}
it(
'can run inside fakeAsync zone',
withProxyZone(
fakeAsync(() => {
TestBed.configureTestingModule({
providers: [provideZoneChangeDetection({scheduleInRootZone: false} as any)],
});
let didRun = false;
@Component({template: ''})
class App {
ngDoCheck() {
didRun = true;
}
}
// create component runs inside the zone and triggers CD as a result
const fixture = TestBed.createComponent(App);
didRun = false;
// create component runs inside the zone and triggers CD as a result
const fixture = TestBed.createComponent(App);
didRun = false;
// schedules change detection
fixture.debugElement.injector.get(ChangeDetectorRef).markForCheck();
expect(didRun).toBe(false);
tick();
expect(didRun).toBe(true);
}));
// schedules change detection
fixture.debugElement.injector.get(ChangeDetectorRef).markForCheck();
expect(didRun).toBe(false);
tick();
expect(didRun).toBe(true);
}),
),
);
describe('explicit ApplicationRef.tick from outside the Angular zone', () => {
function collectErrors(): unknown[] {
+37 -30
View File
@@ -32,6 +32,8 @@ import {
withModule,
} from '../testing';
const {withProxyZone} = (Zone as any)[Zone.__symbol__('fakeAsyncTest')];
@Component({
template: `<span>Original {{ simpleBinding }}</span>`,
})
@@ -348,36 +350,41 @@ describe('ComponentFixture', () => {
expect(() => fixture.detectChanges()).toThrow();
});
it('should not duplicate errors when used with fake async', fakeAsync(() => {
@Component({
template: '<button (click)="doThrow()">a</button>',
})
class Throwing {
doThrow() {
throw new Error('thrown');
}
}
TestBed.configureTestingModule({
providers: [
{
provide: ErrorHandler,
useClass: class {
handleError(e: unknown) {
throw e;
}
},
},
],
});
const fix = TestBed.createComponent(Throwing);
try {
fix.nativeElement.querySelector('button').click();
tick();
fail('should have thrown');
} catch (e) {
expect((e as Error).message).toMatch('thrown');
}
}));
it(
'should not duplicate errors when used with fake async',
withProxyZone(
fakeAsync(() => {
@Component({
template: '<button (click)="doThrow()">a</button>',
})
class Throwing {
doThrow() {
throw new Error('thrown');
}
}
TestBed.configureTestingModule({
providers: [
{
provide: ErrorHandler,
useClass: class {
handleError(e: unknown) {
throw e;
}
},
},
],
});
const fix = TestBed.createComponent(Throwing);
try {
fix.nativeElement.querySelector('button').click();
tick();
fail('should have thrown');
} catch (e) {
expect((e as Error).message).toMatch('thrown');
}
}),
),
);
describe('errors during ApplicationRef.tick', () => {
@Component({
+33
View File
@@ -0,0 +1,33 @@
load("//tools:defaults.bzl", "ts_project", "zoneless_jasmine_test", "zoneless_web_test_suite")
package(default_visibility = ["//visibility:private"])
ts_project(
name = "debug_lib",
testonly = True,
srcs = glob(
["**/*.ts"],
),
deps = [
"//packages/common",
"//packages/core",
"//packages/core/primitives/devtools",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/private/testing",
],
)
zoneless_jasmine_test(
name = "debug",
data = [
":debug_lib",
],
)
zoneless_web_test_suite(
name = "debug_web",
deps = [
":debug_lib",
],
)
@@ -6,9 +6,9 @@
* found in the LICENSE file at https://angular.dev/license
*/
import {ApplicationInitStatus, PendingTasks, provideZoneChangeDetection} from '../../src/core';
import {ApplicationInitStatus, ApplicationRef, PendingTasks} from '../../src/core';
import {provideStabilityDebugging} from '../../src/application/stability_debug_impl';
import {TestBed, fakeAsync, tick} from '@angular/core/testing';
import {TestBed} from '@angular/core/testing';
describe('provideStabilityDebugging', () => {
let consoleWarnSpy: jasmine.Spy;
@@ -17,21 +17,26 @@ describe('provideStabilityDebugging', () => {
let consoleGroupEndSpy: jasmine.Spy;
beforeEach(() => {
jasmine.clock().install();
spyOn(global, 'Error').and.returnValue({stack: 'fake stack trace', name: 'Error', message: ''});
consoleWarnSpy = spyOn(console, 'warn');
consoleDebugSpy = spyOn(console, 'debug');
consoleInfoSpy = spyOn(console, 'info');
consoleGroupEndSpy = spyOn(console, 'groupEnd');
TestBed.configureTestingModule({
providers: [provideStabilityDebugging(), provideZoneChangeDetection()],
providers: [provideStabilityDebugging()],
});
});
afterEach(() => {
jasmine.clock().uninstall();
});
function runInitializers() {
(TestBed.inject(ApplicationInitStatus) as any).runInitializers();
}
it('should log pending tasks if application does not stabilize', fakeAsync(() => {
it('should log pending tasks if application does not stabilize', () => {
const pendingTasks = TestBed.inject(PendingTasks);
// Prevent stability
@@ -39,15 +44,15 @@ describe('provideStabilityDebugging', () => {
runInitializers();
tick(10_000);
jasmine.clock().tick(10_000);
expect(consoleDebugSpy.calls.first().args[0]).toMatch(/Application did not stabilize/);
expect(consoleDebugSpy.calls.all()[1].args[0]).toMatch(/fake stack trace/);
removeTask();
}));
});
it('should not log if application stabilizes within 9 seconds', fakeAsync(() => {
it('should not log if application stabilizes within 9 seconds', async () => {
const pendingTasks = TestBed.inject(PendingTasks);
// Prevent stability
@@ -55,10 +60,13 @@ describe('provideStabilityDebugging', () => {
runInitializers();
tick(5000);
jasmine.clock().tick(5000);
removeTask(); // Stabilize
tick(4000); // Reach 9000 total
jasmine.clock().tick(0);
await TestBed.inject(ApplicationRef).whenStable();
await Promise.resolve();
jasmine.clock().tick(4000); // Reach 9000 total
expect(consoleDebugSpy).not.toHaveBeenCalled();
}));
});
});
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -39,7 +39,7 @@ import {
provideZoneChangeDetection,
ViewChild,
} from '../../src/core';
import {fakeAsync, flushMicrotasks, TestBed} from '../../testing';
import {TestBed} from '../../testing';
import {HostListener} from '../../src/metadata/directives';
@@ -1278,7 +1278,7 @@ import {HostListener} from '../../src/metadata/directives';
expect(ancestorElm.contains(parentElm)).toBe(false);
});
it('should only retain a to-be-removed node if the inner queried items are apart of an animation issued by an ancestor', fakeAsync(() => {
it('should only retain a to-be-removed node if the inner queried items are apart of an animation issued by an ancestor', async () => {
@Component({
selector: 'ani-cmp',
template: `
@@ -1340,7 +1340,7 @@ import {HostListener} from '../../src/metadata/directives';
let childPlayerComplete = false;
childPlayer.onDone(() => (childPlayerComplete = true));
resetLog();
flushMicrotasks();
await Promise.resolve();
expect(childPlayerComplete).toBe(false);
@@ -1353,7 +1353,7 @@ import {HostListener} from '../../src/metadata/directives';
expect(twoPlayers.length).toEqual(1); // the header element
expect(ancestorElm.contains(parentElm)).toBe(false);
expect(childPlayerComplete).toBe(true);
}));
});
it('should finish queried players in an animation when the next animation takes over', () => {
@Component({
@@ -2349,7 +2349,7 @@ import {HostListener} from '../../src/metadata/directives';
expect(p1cp.element.classList.contains('child')).toBeTruthy();
});
it('should emulate a leave animation on the nearest sub host elements when a parent is removed', fakeAsync(() => {
it('should emulate a leave animation on the nearest sub host elements when a parent is removed', async () => {
@Component({
selector: 'ani-cmp',
template: `
@@ -2409,13 +2409,13 @@ import {HostListener} from '../../src/metadata/directives';
cmp.exp = false;
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
expect(cmp.childEvent.toState).toEqual('void');
expect(cmp.childEvent.totalTime).toEqual(1000);
expect(childCmp.childEvent.toState).toEqual('void');
expect(childCmp.childEvent.totalTime).toEqual(1000);
}));
});
it("should emulate a leave animation on a sub component's inner elements when a parent leave animation occurs with animateChild", () => {
@Component({
@@ -2563,7 +2563,7 @@ import {HostListener} from '../../src/metadata/directives';
]);
});
it('should not cause a removal of inner @trigger DOM nodes when a parent animation occurs', fakeAsync(() => {
it('should not cause a removal of inner @trigger DOM nodes when a parent animation occurs', async () => {
@Component({
selector: 'ani-cmp',
template: `
@@ -2597,18 +2597,18 @@ import {HostListener} from '../../src/metadata/directives';
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
cmp.exp = false;
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
const players = getLog();
expect(players.length).toEqual(1);
const element = players[0].element;
expect(element.innerText.trim()).toMatch(/this\s+child/gm);
}));
});
it('should only mark outermost *directive nodes :enter and :leave when inserts and removals occur', () => {
@Component({
@@ -2787,7 +2787,7 @@ import {HostListener} from '../../src/metadata/directives';
expect(p3.element.classList.contains('page2')).toBe(true);
});
it('should emulate leave animation callbacks for all sub elements that have leave triggers within the component', fakeAsync(() => {
it('should emulate leave animation callbacks for all sub elements that have leave triggers within the component', async () => {
@Component({
selector: 'ani-cmp',
animations: [
@@ -2845,12 +2845,12 @@ import {HostListener} from '../../src/metadata/directives';
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
cmp.log = [];
cmp.exp = false;
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
expect(cmp.log).toEqual([
'c1-start',
'c1-done',
@@ -2861,7 +2861,7 @@ import {HostListener} from '../../src/metadata/directives';
'c3-done',
'p-done',
]);
}));
});
it('should build, but not run sub triggers when a parent animation is scheduled', () => {
@Component({
@@ -2917,7 +2917,7 @@ import {HostListener} from '../../src/metadata/directives';
expect((engine.players[0] as TransitionAnimationPlayer).getRealPlayer()).toBe(players[1]);
});
it('should fire and synchronize the start/done callbacks on sub triggers even if they are not allowed to animate within the animation', fakeAsync(() => {
it('should fire and synchronize the start/done callbacks on sub triggers even if they are not allowed to animate within the animation', async () => {
@Component({
selector: 'parent-cmp',
animations: [
@@ -2981,7 +2981,7 @@ import {HostListener} from '../../src/metadata/directives';
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(ParentCmp);
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
const cmp = fixture.componentInstance;
const child = cmp.childCmp;
@@ -2994,7 +2994,7 @@ import {HostListener} from '../../src/metadata/directives';
cmp.exp = 'go';
cmp.childCmp.exp = 'go';
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
expect(cmp.log).toEqual(['parent-start']);
expect(child.log).toEqual(['child-start']);
@@ -3010,13 +3010,13 @@ import {HostListener} from '../../src/metadata/directives';
child.log = [];
cmp.remove = true;
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
expect(cmp.log).toEqual(['parent-start', 'parent-done']);
expect(child.log).toEqual(['child-start', 'child-done']);
}));
});
it('should fire and synchronize the start/done callbacks on multiple blocked sub triggers', fakeAsync(() => {
it('should fire and synchronize the start/done callbacks on multiple blocked sub triggers', async () => {
@Component({
selector: 'cmp',
animations: [
@@ -3079,7 +3079,7 @@ import {HostListener} from '../../src/metadata/directives';
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
const cmp = fixture.componentInstance;
cmp.log = [];
@@ -3088,7 +3088,7 @@ import {HostListener} from '../../src/metadata/directives';
cmp.child1Exp = 'go';
cmp.child2Exp = 'go';
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
expect(cmp.log).toEqual(['parent1-start', 'parent2-start', 'child1-start', 'child2-start']);
@@ -3097,8 +3097,8 @@ import {HostListener} from '../../src/metadata/directives';
cmp.child1Exp = 'go-again';
cmp.child2Exp = 'go-again';
fixture.detectChanges();
flushMicrotasks();
}));
await Promise.resolve();
});
it('should stretch the starting keyframe of a child animation queries are issued by the parent', () => {
@Component({
@@ -3402,7 +3402,7 @@ import {HostListener} from '../../src/metadata/directives';
expect(pcp.element.classList.contains('item')).toBeTruthy();
});
it('should correctly remove a leaving element queried/animated by a parent queried via animateChild', fakeAsync(() => {
it('should correctly remove a leaving element queried/animated by a parent queried via animateChild', async () => {
@Component({
selector: 'cmp',
template: `
@@ -3442,13 +3442,13 @@ import {HostListener} from '../../src/metadata/directives';
cmp.childPresent = false;
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
engine.players.forEach((player) => player.finish());
children = fixture.debugElement.nativeElement.querySelectorAll('.child');
expect(children.length).toEqual(0);
}));
});
it('should correctly animate state styles of the root element applied via animate inside a group (independently of the order)', () => {
@Component({
@@ -23,7 +23,7 @@ import {
} from '@angular/animations/browser';
import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing';
import {Component, HostBinding} from '../../src/core';
import {fakeAsync, flushMicrotasks, TestBed, tick} from '../../testing';
import {TestBed} from '../../testing';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {ActivatedRoute, Router, RouterModule, RouterOutlet} from '@angular/router';
import {isNode} from '@angular/private/testing';
@@ -49,7 +49,7 @@ import {isNode} from '@angular/private/testing';
});
});
it('should query the old and new routes via :leave and :enter', fakeAsync(() => {
it('should query the old and new routes via :leave and :enter', async () => {
@Component({
animations: [
trigger('routerAnimations', [
@@ -118,17 +118,15 @@ import {isNode} from '@angular/private/testing';
const fixture = TestBed.createComponent(ContainerCmp);
const cmp = fixture.componentInstance;
cmp.router.initialNavigation();
tick();
await fixture.whenStable();
fixture.detectChanges();
engine.flush();
cmp.router.navigateByUrl('/page1');
tick();
await cmp.router.navigateByUrl('/page1');
fixture.detectChanges();
engine.flush();
cmp.router.navigateByUrl('/page2');
tick();
await cmp.router.navigateByUrl('/page2');
fixture.detectChanges();
engine.flush();
@@ -168,9 +166,9 @@ import {isNode} from '@angular/private/testing';
['opacity', '1'],
]),
]);
}));
});
it('should allow inner enter animations to be emulated within a routed item', fakeAsync(() => {
it('should allow inner enter animations to be emulated within a routed item', async () => {
@Component({
animations: [
trigger('routerAnimations', [
@@ -242,17 +240,15 @@ import {isNode} from '@angular/private/testing';
const fixture = TestBed.createComponent(ContainerCmp);
const cmp = fixture.componentInstance;
cmp.router.initialNavigation();
tick();
await fixture.whenStable();
fixture.detectChanges();
engine.flush();
cmp.router.navigateByUrl('/page1');
tick();
await cmp.router.navigateByUrl('/page1');
fixture.detectChanges();
engine.flush();
cmp.router.navigateByUrl('/page2');
tick();
await cmp.router.navigateByUrl('/page2');
fixture.detectChanges();
engine.flush();
@@ -290,9 +286,9 @@ import {isNode} from '@angular/private/testing';
['opacity', '1'],
]),
]);
}));
});
it('should allow inner leave animations to be emulated within a routed item', fakeAsync(() => {
it('should allow inner leave animations to be emulated within a routed item', async () => {
@Component({
animations: [
trigger('routerAnimations', [
@@ -364,17 +360,15 @@ import {isNode} from '@angular/private/testing';
const fixture = TestBed.createComponent(ContainerCmp);
const cmp = fixture.componentInstance;
cmp.router.initialNavigation();
tick();
await fixture.whenStable();
fixture.detectChanges();
engine.flush();
cmp.router.navigateByUrl('/page1');
tick();
await cmp.router.navigateByUrl('/page1');
fixture.detectChanges();
engine.flush();
cmp.router.navigateByUrl('/page2');
tick();
await cmp.router.navigateByUrl('/page2');
fixture.detectChanges();
engine.flush();
@@ -412,9 +406,9 @@ import {isNode} from '@angular/private/testing';
['opacity', '0'],
]),
]);
}));
});
it('should properly collect :enter / :leave router nodes even when another non-router *template component is within the trigger boundaries', fakeAsync(() => {
it('should properly collect :enter / :leave router nodes even when another non-router *template component is within the trigger boundaries', async () => {
@Component({
selector: 'ani-cmp',
animations: [
@@ -478,18 +472,16 @@ import {isNode} from '@angular/private/testing';
const fixture = TestBed.createComponent(ContainerCmp);
const cmp = fixture.componentInstance;
cmp.router.initialNavigation();
tick();
await fixture.whenStable();
fixture.detectChanges();
engine.flush();
cmp.router.navigateByUrl('/page1');
tick();
await cmp.router.navigateByUrl('/page1');
cmp.loading = true;
fixture.detectChanges();
engine.flush();
cmp.router.navigateByUrl('/page2');
tick();
await cmp.router.navigateByUrl('/page2');
cmp.loading = false;
fixture.detectChanges();
engine.flush();
@@ -506,9 +498,9 @@ import {isNode} from '@angular/private/testing';
const [ip1, ip2] = innerPlayers as any;
expect(ip1.element.innerText).toEqual('page1');
expect(ip2.element.innerText).toEqual('page2');
}));
});
it('should allow a recursive set of :leave animations to occur for nested routes', fakeAsync(() => {
it('should allow a recursive set of :leave animations to occur for nested routes', async () => {
@Component({
selector: 'ani-cmp',
template: '<router-outlet name="recur"></router-outlet>',
@@ -519,11 +511,11 @@ import {isNode} from '@angular/private/testing';
log: string[] = [];
enter() {
this._router.navigateByUrl('/(recur:recur/nested)');
return this._router.navigateByUrl('/(recur:recur/nested)');
}
leave() {
this._router.navigateByUrl('/');
return this._router.navigateByUrl('/');
}
}
@@ -575,15 +567,13 @@ import {isNode} from '@angular/private/testing';
const fixture = TestBed.createComponent(ContainerCmp);
const cmp = fixture.componentInstance;
cmp.enter();
tick();
await cmp.enter();
fixture.detectChanges();
flushMicrotasks();
await Promise.resolve();
expect(cmp.log).toEqual(['DEPTH 0', 'DEPTH 1']);
cmp.leave();
tick();
await cmp.leave();
fixture.detectChanges();
const players = getLog();
@@ -592,7 +582,7 @@ import {isNode} from '@angular/private/testing';
const [p1, p2] = players;
expect(p1.element.getAttribute('data-depth')).toEqual('0');
expect(p2.element.getAttribute('data-depth')).toEqual('1');
}));
});
});
});
@@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.dev/license
*/
import {timeout} from '@angular/private/testing';
import {EventEmitter} from '../../src/core';
import {Injectable} from '../../src/di';
import {PendingTasks} from '../../src/pending_tasks';
@@ -19,7 +20,7 @@ import {
setTestabilityGetter,
} from '../../src/testability/testability';
import {NgZone} from '../../src/zone/ng_zone';
import {fakeAsync, tick, waitForAsync, TestBed} from '../../testing';
import {TestBed} from '../../testing';
// Schedules a microtasks (using queueMicrotask)
function microTask(fn: Function): void {
@@ -70,7 +71,7 @@ describe('TestabilityRegistry', () => {
let registry: TestabilityRegistry;
let ngZone: MockNgZone;
beforeEach(waitForAsync(() => {
beforeEach(() => {
ngZone = new MockNgZone();
registry = new TestabilityRegistry();
TestBed.configureTestingModule({
@@ -81,7 +82,7 @@ describe('TestabilityRegistry', () => {
});
testability1 = TestBed.inject(Testability);
testability2 = TestBed.inject(Testability);
}));
});
afterEach(() => {
// Instantiating the Testability (via `new Testability` above) has a side
// effect of defining the testability getter globally to a specified value.
@@ -127,7 +128,7 @@ describe('Testability with PendingTasks', () => {
let pendingTasks: PendingTasks;
let ngZone: MockNgZone;
beforeEach(waitForAsync(() => {
beforeEach(async () => {
ngZone = new MockNgZone();
TestBed.configureTestingModule({
providers: [
@@ -142,61 +143,61 @@ describe('Testability with PendingTasks', () => {
execute = jasmine.createSpy('execute');
execute2 = jasmine.createSpy('execute2');
updateCallback = jasmine.createSpy('updateCallback');
}));
await Promise.resolve();
});
describe('NgZone callback logic', () => {
describe('whenStable with timeout', () => {
it('should fire if Angular is already stable', waitForAsync(() => {
it('should fire if Angular is already stable', async () => {
testability.whenStable(execute, 200);
microTask(() => {
expect(execute).toHaveBeenCalled();
});
}));
it('should fire when macroTasks are cancelled', fakeAsync(() => {
const id = ngZone.run(() => setTimeout(() => {}, 1000));
testability.whenStable(execute, 500);
tick(200);
ngZone.run(() => clearTimeout(id));
// fakeAsync doesn't trigger NgZones whenStable
pendingTasks.add()();
tick(1);
await new Promise<void>((resolve) => microTask(resolve));
expect(execute).toHaveBeenCalled();
}));
});
it('calls the done callback when angular is stable', fakeAsync(() => {
let timeout1Done = false;
ngZone.run(() => setTimeout(() => (timeout1Done = true), 500));
testability.whenStable(execute, 1000);
it('should fire when macroTasks are cancelled', async () => {
const id = ngZone.run(() => setTimeout(() => {}, 100));
testability.whenStable(execute, 50);
tick(600);
await timeout(20);
ngZone.run(() => clearTimeout(id));
// cancelling a macrotask doesn't trigger NgZone's onStable
pendingTasks.add()();
tick();
await timeout(1);
expect(execute).toHaveBeenCalled();
});
it('calls the done callback when angular is stable', async () => {
let timeout1Done = false;
ngZone.run(() => setTimeout(() => (timeout1Done = true), 25));
testability.whenStable(execute, 50);
await timeout(30);
pendingTasks.add()();
await timeout();
expect(timeout1Done).toEqual(true);
expect(execute).toHaveBeenCalled();
// Should cancel the done timeout.
tick(500);
await timeout(25);
pendingTasks.add()();
tick();
await timeout();
expect(execute.calls.count()).toEqual(1);
}));
});
it('calls update when macro tasks change', fakeAsync(() => {
it('calls update when macro tasks change', async () => {
let timeout1Done = false;
let timeout2Done = false;
ngZone.run(() => setTimeout(() => (timeout1Done = true), 500));
tick();
testability.whenStable(execute, 1000, updateCallback);
ngZone.run(() => setTimeout(() => (timeout1Done = true), 25));
await timeout();
testability.whenStable(execute, 50, updateCallback);
tick(100);
ngZone.run(() => setTimeout(() => (timeout2Done = true), 300));
await timeout(5);
ngZone.run(() => setTimeout(() => (timeout2Done = true), 15));
expect(updateCallback.calls.count()).toEqual(1);
tick(600);
await timeout(30);
expect(timeout1Done).toEqual(true);
expect(timeout2Done).toEqual(true);
@@ -204,40 +205,41 @@ describe('Testability with PendingTasks', () => {
expect(execute).toHaveBeenCalled();
const update1 = updateCallback.calls.all()[0].args[0] as PendingMacrotask[];
expect(update1[0].data!.delay).toEqual(500);
expect(update1[0].data!.delay).toEqual(25);
const update2 = updateCallback.calls.all()[1].args[0] as PendingMacrotask[];
expect(update2[0].data!.delay).toEqual(500);
expect(update2[1].data!.delay).toEqual(300);
}));
expect(update2[0].data!.delay).toEqual(25);
expect(update2[1].data!.delay).toEqual(15);
});
it('cancels the done callback if the update callback returns true', fakeAsync(() => {
it('cancels the done callback if the update callback returns true', async () => {
let timeoutDone = false;
const task = pendingTasks.add();
execute2.and.returnValue(true);
testability.whenStable(execute, 1000, execute2);
testability.whenStable(execute, 50, execute2);
tick(100);
ngZone.run(() => setTimeout(() => (timeoutDone = true), 500));
await timeout(5);
ngZone.run(() => setTimeout(() => (timeoutDone = true), 25));
task();
await timeout();
expect(execute2).toHaveBeenCalled();
tick(500);
await timeout(25);
pendingTasks.add()();
tick();
await timeout();
expect(execute).not.toHaveBeenCalled();
}));
});
});
it('should fire whenstable callback if event is already finished', fakeAsync(() => {
it('should fire whenstable callback if event is already finished', async () => {
const task = pendingTasks.add();
task();
testability.whenStable(execute);
tick();
await timeout();
expect(execute).toHaveBeenCalled();
}));
});
it('should not fire whenstable callbacks synchronously if event is already finished', () => {
const task = pendingTasks.add();
@@ -247,17 +249,17 @@ describe('Testability with PendingTasks', () => {
expect(execute).not.toHaveBeenCalled();
});
it('should fire whenstable callback when event finishes', fakeAsync(() => {
it('should fire whenstable callback when event finishes', async () => {
const task = pendingTasks.add();
testability.whenStable(execute);
tick();
await timeout();
expect(execute).not.toHaveBeenCalled();
task();
tick();
await timeout();
expect(execute).toHaveBeenCalled();
}));
});
it('should not fire whenstable callbacks synchronously when event finishes', () => {
const task = pendingTasks.add();
@@ -267,46 +269,46 @@ describe('Testability with PendingTasks', () => {
expect(execute).not.toHaveBeenCalled();
});
it('should fire whenstable callback with didWork if event is already finished', fakeAsync(() => {
it('should fire whenstable callback with didWork if event is already finished', async () => {
const task = pendingTasks.add();
task();
testability.whenStable(execute);
tick();
await timeout();
expect(execute).toHaveBeenCalled();
testability.whenStable(execute2);
tick();
await timeout();
expect(execute2).toHaveBeenCalled();
}));
});
it('should fire whenstable callback with didwork when event finishes', fakeAsync(() => {
it('should fire whenstable callback with didwork when event finishes', async () => {
const task = pendingTasks.add();
testability.whenStable(execute);
tick();
await timeout();
task();
tick();
await timeout();
expect(execute).toHaveBeenCalled();
testability.whenStable(execute2);
tick();
await timeout();
expect(execute2).toHaveBeenCalled();
}));
});
});
it('should consider pending tasks when enabled', fakeAsync(() => {
it('should consider pending tasks when enabled', async () => {
const task = pendingTasks.add();
testability.whenStable(execute);
tick();
await timeout();
expect(execute).not.toHaveBeenCalled();
task();
tick();
await timeout();
expect(execute).toHaveBeenCalled();
}));
});
});
describe('Testability with PendingTasks disabled', () => {
@@ -315,7 +317,7 @@ describe('Testability with PendingTasks disabled', () => {
let pendingTasks: PendingTasks;
let ngZone: MockNgZone;
beforeEach(waitForAsync(() => {
beforeEach(async () => {
ngZone = new MockNgZone();
TestBed.configureTestingModule({
providers: [
@@ -328,14 +330,15 @@ describe('Testability with PendingTasks disabled', () => {
pendingTasks = TestBed.inject(PendingTasks);
testability = TestBed.inject(Testability);
execute = jasmine.createSpy('execute');
}));
await Promise.resolve();
});
it('should ignore pending tasks when Zone is present by default', fakeAsync(() => {
it('should ignore pending tasks when Zone is present by default', async () => {
const task = pendingTasks.add();
testability.whenStable(execute);
tick();
await timeout();
expect(execute).toHaveBeenCalled();
task();
}));
});
});
+19 -17
View File
@@ -11,7 +11,7 @@ import type {} from 'zone.js';
import {firstValueFrom} from 'rxjs';
import {Component, EventEmitter, NgZone, provideZoneChangeDetection} from '../../src/core';
import {TestBed, fakeAsync, flush, flushMicrotasks, waitForAsync} from '../../testing';
import {TestBed} from '../../testing';
import {Log} from '../../testing/src/testing_internal';
import {isBrowser} from '@angular/private/testing';
@@ -886,15 +886,13 @@ function commonTests() {
ngZone = TestBed.inject(NgZone);
});
it('should fakeAsync even if the NgZone was created outside.', fakeAsync(() => {
it('should fakeAsync even if the NgZone was created outside.', async () => {
let result: string = null!;
// try to escape the current fakeAsync zone by using NgZone which was created outside.
ngZone.run(() => {
Promise.resolve('works').then((v) => (result = v));
flushMicrotasks();
await ngZone.run(() => {
return Promise.resolve('works').then((v) => (result = v));
});
expect(result).toEqual('works');
}));
});
describe('async', () => {
let asyncResult: string;
@@ -904,14 +902,18 @@ function commonTests() {
asyncResult = null!;
});
it('should async even if the NgZone was created outside.', waitForAsync(() => {
// try to escape the current async zone by using NgZone which was created outside.
ngZone.run(() => {
setTimeout(() => {
Promise.resolve('works').then((v) => (asyncResult = v));
}, waitLongerThenTestFrameworkAsyncTimeout);
it('should async even if the NgZone was created outside.', async () => {
await new Promise<void>((resolve) => {
ngZone.run(() => {
setTimeout(() => {
Promise.resolve('works').then((v) => {
asyncResult = v;
resolve();
});
}, waitLongerThenTestFrameworkAsyncTimeout);
});
});
}));
});
afterEach(() => {
expect(asyncResult).toEqual('works');
@@ -919,7 +921,7 @@ function commonTests() {
});
});
it('coalescing can work with fakeAsync', fakeAsync(() => {
it('coalescing can work with fakeAsync', async () => {
if (!isBrowser) {
return;
}
@@ -941,9 +943,9 @@ function commonTests() {
fixture.autoDetectChanges();
document.querySelector('.clickable')!.dispatchEvent(new MouseEvent('click'));
flush();
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toContain('clicked');
}));
});
});
describe('coalescing', () => {
@@ -9,4 +9,15 @@
// Import the "fake_async" example that registers tests which are shown as examples. These need
// to be valid tests, so we run them here. Note that we need to add this layer of abstraction here
// because the "jasmine_test" rule only picks up test files with the "_spec.ts" file suffix.
import './fake_async';
declare const Zone: any;
declare const require: any;
const ProxyZoneSpec: {new (): any} = Zone['ProxyZoneSpec'];
const proxyZone = Zone.root.fork(new ProxyZoneSpec());
const originalIt = it;
(globalThis as any).it = function (desc: string, fn: any) {
return originalIt(desc, function (this: any) {
return proxyZone.run(fn, this, arguments as any);
});
};
require('./fake_async');
File diff suppressed because it is too large Load Diff
@@ -14,7 +14,7 @@ import {
NgModule,
provideZonelessChangeDetection,
} from '@angular/core';
import {fakeAsync, TestBed, tick} from '@angular/core/testing';
import {TestBed} from '@angular/core/testing';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {BrowserTestingModule, platformBrowserTesting} from '@angular/platform-browser/testing';
import {isBrowser} from '@angular/private/testing';
@@ -79,15 +79,14 @@ if (isBrowser) {
expect(resourceLoader instanceof ResourceLoaderImpl).toBeTruthy();
});
it('should allow the use of fakeAsync', fakeAsync(() => {
it('should allow the use of async/await', async () => {
const service = TestBed.inject(FancyService);
let value: string | undefined;
service.getAsyncValue().then(function (val: string) {
await service.getAsyncValue().then(function (val: string) {
value = val;
});
tick();
expect(value).toEqual('async value');
}));
});
afterEach(() => {
getPlatform()?.destroy();
File diff suppressed because it is too large Load Diff
+6 -7
View File
@@ -8,7 +8,7 @@
import {Location} from '@angular/common';
import {$locationShim, UrlCodec} from '@angular/common/upgrade';
import {fakeAsync, flush, TestBed} from '@angular/core/testing';
import {TestBed} from '@angular/core/testing';
import {Router, RouterModule} from '../../index';
import {setUpLocationSync} from '../../upgrade';
import {UpgradeModule} from '@angular/upgrade/static';
@@ -169,7 +169,7 @@ describe('setUpLocationSync', () => {
}
});
it('should not duplicate navigations triggered by Angular router', fakeAsync(() => {
it('should not duplicate navigations triggered by Angular router', async () => {
spyOn(TestBed.inject(UrlCodec), 'parse').and.returnValue({
pathname: '',
href: '',
@@ -186,20 +186,19 @@ describe('setUpLocationSync', () => {
// Inject location shim so its urlChangeListener subscribes
TestBed.inject($locationShim);
router.navigateByUrl('/1');
location.normalize.and.returnValue('/1');
flush();
await router.navigateByUrl('/1');
expect(router.navigateByUrl).toHaveBeenCalledTimes(1);
expect($rootScope.$broadcast.calls.argsFor(0)[0]).toEqual('$locationChangeStart');
expect($rootScope.$broadcast.calls.argsFor(1)[0]).toEqual('$locationChangeSuccess');
$rootScope.$broadcast.calls.reset();
router.navigateByUrl.calls.reset();
location.go('/2');
location.normalize.and.returnValue('/2');
flush();
location.go('/2');
expect($rootScope.$broadcast.calls.argsFor(0)[0]).toEqual('$locationChangeStart');
expect($rootScope.$broadcast.calls.argsFor(1)[0]).toEqual('$locationChangeSuccess');
expect(router.navigateByUrl).toHaveBeenCalledTimes(1);
}));
await router.navigateByUrl.calls.mostRecent().returnValue;
});
});
+2 -2
View File
@@ -1,4 +1,4 @@
load("//tools:defaults.bzl", "ng_web_test_suite", "ts_project", "zoneless_jasmine_test")
load("//tools:defaults.bzl", "ts_project", "zoneless_jasmine_test", "zoneless_web_test_suite")
ts_project(
name = "test_lib",
@@ -25,7 +25,7 @@ zoneless_jasmine_test(
],
)
ng_web_test_suite(
zoneless_web_test_suite(
name = "test_web",
deps = [
":test_lib",
+71 -54
View File
@@ -7,7 +7,7 @@
*/
import {ApplicationRef, PLATFORM_ID} from '@angular/core';
import {fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing';
import {TestBed} from '@angular/core/testing';
import {Subject} from 'rxjs';
import {filter, take} from 'rxjs/operators';
@@ -19,8 +19,9 @@ const provideServiceWorkerApi = 'provideServiceWorker';
const serviceWorkerModuleApi = 'ServiceWorkerModule';
async function waitForReadyToRegister() {
// `readyToRegister` is a microtask, so we wait for it to execute by
// scheduling another microtask before running expectations.
// `readyToRegister` is a microtask (often via `Promise.race`), so we wait for it to execute by
// scheduling microtasks before running expectations.
await Promise.resolve();
await Promise.resolve();
}
@@ -230,10 +231,17 @@ async function waitForReadyToRegister() {
});
describe('registrationStrategy', () => {
beforeEach(() => jasmine.clock().install());
afterEach(() => jasmine.clock().uninstall());
const configTestBedWithMockedStability = (
strategy?: SwRegistrationOptions['registrationStrategy'],
) => {
const isStableSub = new Subject<boolean>();
const whenStable = () =>
new Promise<void>((resolve) =>
isStableSub.pipe(filter(Boolean), take(1)).subscribe(() => resolve()),
);
if (apiFnName === provideServiceWorkerApi) {
TestBed.configureTestingModule({
@@ -243,7 +251,7 @@ async function waitForReadyToRegister() {
provide: ApplicationRef,
useValue: {
isStable: isStableSub.asObservable(),
whenStable: () => isStableSub.pipe(filter(Boolean), take(1)),
whenStable,
afterTick: new Subject(),
onDestroy: () => {},
},
@@ -263,7 +271,7 @@ async function waitForReadyToRegister() {
provide: ApplicationRef,
useValue: {
isStable: isStableSub.asObservable(),
whenStable: () => isStableSub.pipe(filter(Boolean), take(1)),
whenStable,
afterTick: new Subject(),
onDestroy: () => {},
},
@@ -283,117 +291,128 @@ async function waitForReadyToRegister() {
return isStableSub;
};
it('defaults to registering the SW when the app stabilizes (under 30s)', fakeAsync(() => {
it('defaults to registering the SW when the app stabilizes (under 30s)', async () => {
const isStableSub = configTestBedWithMockedStability();
isStableSub.next(false);
jasmine.clock().tick(20000);
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
// tick(20000);
// Calling `tick(20000)` drains the microtask queue,
// which leads to `register` being called.
isStableSub.next(true);
await waitForReadyToRegister();
tick();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('defaults to registering the SW after 30s if the app does not stabilize sooner', fakeAsync(() => {
it('defaults to registering the SW after 30s if the app does not stabilize sooner', async () => {
configTestBedWithMockedStability();
jasmine.clock().tick(29999);
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
tick(30000);
jasmine.clock().tick(1);
await waitForReadyToRegister();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('registers the SW when the app stabilizes with `registerWhenStable:<timeout>`', fakeAsync(() => {
it('registers the SW when the app stabilizes with `registerWhenStable:<timeout>`', async () => {
const isStableSub = configTestBedWithMockedStability('registerWhenStable:1000');
isStableSub.next(false);
isStableSub.next(false);
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
isStableSub.next(true);
await waitForReadyToRegister();
tick();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('registers the SW after `timeout` if the app does not stabilize with `registerWhenStable:<timeout>`', fakeAsync(() => {
it('registers the SW after `timeout` if the app does not stabilize with `registerWhenStable:<timeout>`', async () => {
configTestBedWithMockedStability('registerWhenStable:1000');
jasmine.clock().tick(999);
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
tick(1000);
jasmine.clock().tick(1);
await waitForReadyToRegister();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('registers the SW asap (asynchronously) before the app stabilizes with `registerWhenStable:0`', fakeAsync(() => {
it('registers the SW asap (asynchronously) before the app stabilizes with `registerWhenStable:0`', async () => {
configTestBedWithMockedStability('registerWhenStable:0');
// Create a microtask.
Promise.resolve();
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
tick(0);
jasmine.clock().tick(0);
await waitForReadyToRegister();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('registers the SW only when the app stabilizes with `registerWhenStable:`', fakeAsync(() => {
it('registers the SW only when the app stabilizes with `registerWhenStable:`', async () => {
const isStableSub = configTestBedWithMockedStability('registerWhenStable:');
isStableSub.next(false);
isStableSub.next(false);
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
isStableSub.next(true);
await waitForReadyToRegister();
tick();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('registers the SW only when the app stabilizes with `registerWhenStable`', fakeAsync(() => {
it('registers the SW only when the app stabilizes with `registerWhenStable`', async () => {
const isStableSub = configTestBedWithMockedStability('registerWhenStable');
isStableSub.next(false);
isStableSub.next(false);
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
isStableSub.next(true);
await waitForReadyToRegister();
tick();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('registers the SW immediatelly (synchronously) with `registerImmediately`', async () => {
configTestBedWithMockedStability('registerImmediately');
@@ -405,72 +424,70 @@ async function waitForReadyToRegister() {
});
});
it('registers the SW after the specified delay with `registerWithDelay:<delay>`', fakeAsync(() => {
it('registers the SW after the specified delay with `registerWithDelay:<delay>`', async () => {
configTestBedWithMockedStability('registerWithDelay:100000');
// tick(99999);
// Calling `tick(99999)` drains the microtask queue,
// which leads to `register` being called.
jasmine.clock().tick(99999);
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
tick(100000);
jasmine.clock().tick(1);
await waitForReadyToRegister();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('registers the SW asap (asynchronously) with `registerWithDelay:`', fakeAsync(() => {
it('registers the SW asap (asynchronously) with `registerWithDelay:`', async () => {
configTestBedWithMockedStability('registerWithDelay:');
// Create a microtask.
Promise.resolve();
flushMicrotasks();
// Wait for microtasks.
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
tick(0);
jasmine.clock().tick(0);
await waitForReadyToRegister();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('registers the SW asap (asynchronously) with `registerWithDelay`', fakeAsync(() => {
it('registers the SW asap (asynchronously) with `registerWithDelay`', async () => {
configTestBedWithMockedStability('registerWithDelay');
// Create a microtask.
Promise.resolve();
flushMicrotasks();
// Wait for microtasks.
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
tick(0);
jasmine.clock().tick(0);
await waitForReadyToRegister();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('registers the SW on first emitted value with observable factory function', fakeAsync(() => {
it('registers the SW on first emitted value with observable factory function', async () => {
const registerSub = new Subject<void>();
const isStableSub = configTestBedWithMockedStability(() => registerSub.asObservable());
isStableSub.next(true);
tick();
await waitForReadyToRegister();
expect(swRegisterSpy).not.toHaveBeenCalled();
registerSub.next();
tick();
await waitForReadyToRegister();
expect(swRegisterSpy).toHaveBeenCalledWith('sw.js', {
scope: undefined,
updateViaCache: undefined,
type: undefined,
});
}));
});
it('throws an error with unknown strategy', () => {
expect(() => configTestBedWithMockedStability('registerYesterday')).toThrowError(
@@ -19,9 +19,9 @@ import {
provideZoneChangeDetection,
SimpleChanges,
} from '@angular/core';
import {waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {timeout} from '@angular/private/testing';
import {downgradeComponent, UpgradeComponent, UpgradeModule} from '../../../static';
import * as angular from '../../../src/common/src/angular1';
@@ -34,7 +34,7 @@ withEachNg1Version(() => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should not break if a $digest is already in progress', waitForAsync(() => {
it('should not break if a $digest is already in progress', async () => {
const element = html('<my-app></my-app>');
@Component({
@@ -58,45 +58,41 @@ withEachNg1Version(() => {
.module_('ng1', [])
.directive('myApp', downgradeComponent({component: AppComponent}));
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService;
const ngZone: NgZone = upgrade.ngZone;
const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module);
const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService;
const ngZone: NgZone = upgrade.ngZone;
// Wrap in a setTimeout to ensure all bootstrap operations have completed.
setTimeout(
// Run inside the Angular zone, so that operations such as emitting
// `onMicrotaskEmpty` do not trigger entering/existing the zone (and thus another
// `$digest`). This also closer simulates what would happen in a real app.
() =>
ngZone.run(() => {
const digestSpy = spyOn($rootScope, '$digest').and.callThrough();
// Wrap in a setTimeout to ensure all bootstrap operations have completed.
await timeout();
// Run inside the Angular zone, so that operations such as emitting
// `onMicrotaskEmpty` do not trigger entering/existing the zone (and thus another
// `$digest`). This also closer simulates what would happen in a real app.
ngZone.run(() => {
const digestSpy = spyOn($rootScope, '$digest').and.callThrough();
// Step 1: Ensure `$digest` is run on `onMicrotaskEmpty`.
ngZone.onMicrotaskEmpty.emit(null);
expect(digestSpy).toHaveBeenCalledTimes(1);
// Step 1: Ensure `$digest` is run on `onMicrotaskEmpty`.
ngZone.onMicrotaskEmpty.emit(null);
expect(digestSpy).toHaveBeenCalledTimes(1);
digestSpy.calls.reset();
digestSpy.calls.reset();
// Step 2: Cause the issue.
$rootScope.$apply(() => ngZone.onMicrotaskEmpty.emit(null));
// Step 2: Cause the issue.
$rootScope.$apply(() => ngZone.onMicrotaskEmpty.emit(null));
// With the fix, `$digest` will only be run once (for `$apply()`).
// Without the fix, `$digest()` would have been run an extra time
// (`onMicrotaskEmpty`).
expect(digestSpy).toHaveBeenCalledTimes(1);
// With the fix, `$digest` will only be run once (for `$apply()`).
// Without the fix, `$digest()` would have been run an extra time
// (`onMicrotaskEmpty`).
expect(digestSpy).toHaveBeenCalledTimes(1);
digestSpy.calls.reset();
digestSpy.calls.reset();
// Step 3: Ensure that `$digest()` is still executed on `onMicrotaskEmpty`.
ngZone.onMicrotaskEmpty.emit(null);
expect(digestSpy).toHaveBeenCalledTimes(1);
}),
0,
);
// Step 3: Ensure that `$digest()` is still executed on `onMicrotaskEmpty`.
ngZone.onMicrotaskEmpty.emit(null);
expect(digestSpy).toHaveBeenCalledTimes(1);
});
}));
});
it('should interleave scope and component expressions', waitForAsync(() => {
it('should interleave scope and component expressions', async () => {
const log: string[] = [];
const l = (value: string) => {
log.push(value);
@@ -152,15 +148,14 @@ withEachNg1Version(() => {
});
const element = html("<div>{{reset(); l('1A');}}<ng2>{{l('1B')}}</ng2>{{l('1C')}}</div>");
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(document.body.textContent).toEqual('1A;2A;ng1a;2B;ng1b;2C;1C;');
expect(log).toEqual(['1A', '1C', '2A', '2B', '2C', 'ng1a', 'ng1b']);
});
}));
await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module);
expect(document.body.textContent).toEqual('1A;2A;ng1a;2B;ng1b;2C;1C;');
expect(log).toEqual(['1A', '1C', '2A', '2B', '2C', 'ng1a', 'ng1b']);
});
it('should propagate changes to a downgraded component inside the ngZone', waitForAsync(() => {
it('should propagate changes to a downgraded component inside the ngZone', async () => {
const element = html('<my-app></my-app>');
let appComponent: AppComponent;
let appComponent!: AppComponent;
@Component({
selector: 'my-app',
@@ -215,10 +210,10 @@ withEachNg1Version(() => {
.module_('ng1', [])
.directive('myApp', downgradeComponent({component: AppComponent}));
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
appComponent.value = 5;
});
}));
await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module);
appComponent.value = 5;
await timeout();
});
// This test demonstrates https://github.com/angular/angular/issues/6385
// which was invalidly fixed by https://github.com/angular/angular/pull/6386
@@ -15,7 +15,6 @@ import {
Input,
NgModule,
} from '@angular/core';
import {waitForAsync} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {downgradeComponent, UpgradeComponent, UpgradeModule} from '../../../static';
@@ -34,7 +33,7 @@ withEachNg1Version(() => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should instantiate ng2 in ng1 template and project content', waitForAsync(() => {
it('should instantiate ng2 in ng1 template and project content', async () => {
// the ng2 component that will be used in ng1 (downgraded)
@Component({
selector: 'ng2',
@@ -67,12 +66,11 @@ withEachNg1Version(() => {
const element = html("<div>{{ 'ng1[' }}<ng2>~{{ ngContent }}~</ng2>{{ ']' }}</div>");
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(document.body.textContent).toEqual('ng1[NG2(~ng1-content~)]');
});
}));
await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module);
expect(document.body.textContent).toEqual('ng1[NG2(~ng1-content~)]');
});
it('should correctly project structural directives', waitForAsync(() => {
it('should correctly project structural directives', async () => {
@Component({
selector: 'ng2',
template: 'ng2-{{ itemId }}(<ng-content></ng-content>)',
@@ -107,12 +105,11 @@ withEachNg1Version(() => {
</ng2>
`);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(multiTrim(document.body.textContent)).toBe('ng2-a( 123 )ng2-b( 456 )ng2-c( 789 )');
});
}));
await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module);
expect(multiTrim(document.body.textContent)).toBe('ng2-a( 123 )ng2-b( 456 )ng2-c( 789 )');
});
it('should instantiate ng1 in ng2 template and project content', waitForAsync(() => {
it('should instantiate ng1 in ng2 template and project content', async () => {
@Component({
selector: 'ng2',
template: `{{ 'ng2(' }}<ng1>{{ transclude }}</ng1
@@ -156,12 +153,11 @@ withEachNg1Version(() => {
const element = html("<div>{{ 'ng1(' }}<ng2></ng2>{{ ')' }}</div>");
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(document.body.textContent).toEqual('ng1(ng2(ng1(ng2-transclude)))');
});
}));
await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module);
expect(document.body.textContent).toEqual('ng1(ng2(ng1(ng2-transclude)))');
});
it('should support multi-slot projection', waitForAsync(() => {
it('should support multi-slot projection', async () => {
@Component({
selector: 'ng2',
template:
@@ -188,9 +184,8 @@ withEachNg1Version(() => {
'<ng2><div ng-if="true" class="ng1a">1a</div><div' + ' class="ng1b">1b</div></ng2>',
);
bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => {
expect(document.body.textContent).toEqual('2a(1a)2b(1b)');
});
}));
await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module);
expect(document.body.textContent).toEqual('2a(1a)2b(1b)');
});
});
});

Some files were not shown because too many files have changed in this diff Show More