From e8a7e49e6bf748ba0c2193c4a994035e41f3fcdf Mon Sep 17 00:00:00 2001 From: Andrew Scott Date: Tue, 20 Oct 2026 23:01:20 +0000 Subject: [PATCH] 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). --- adev/package.json | 4 +- .../services/search-history.service.spec.ts | 2 +- .../references/pipes/api-label.pipe.spec.ts | 2 +- modules/package.json | 2 +- ngp-vscode-ng-language-service/package.json | 2 +- package.json | 6 +- .../test/animation_group_player_spec.ts | 13 +- .../animations/test/animation_player_spec.ts | 25 +- .../test/browser_animation_builder_spec.ts | 50 +- .../rxjs-interop/test/to_observable_spec.ts | 2 +- packages/core/test/acceptance/pipe_spec.ts | 2 +- .../test/change_detection_scheduler_spec.ts | 127 +- packages/core/test/component_fixture_spec.ts | 67 +- packages/core/test/debug/BUILD.bazel | 33 + .../core/test/debug/stability_debug_spec.ts | 28 +- packages/core/test/fake_async_spec.ts | 772 +++++---- .../legacy_animation_integration_spec.ts | 230 +-- ...legacy_animation_query_integration_spec.ts | 56 +- ...egacy_animation_router_integration_spec.ts | 66 +- .../core/test/testability/testability_spec.ts | 151 +- packages/core/test/zone/ng_zone_spec.ts | 36 +- .../examples/core/testing/ts/example_spec.ts | 13 +- .../test/http-client-backend-service_spec.ts | 598 ++++--- .../test/testing_public_browser_spec.ts | 9 +- .../test/testing_public_spec.ts | 219 ++- packages/router/upgrade/test/upgrade.spec.ts | 13 +- packages/service-worker/test/BUILD.bazel | 4 +- packages/service-worker/test/provider_spec.ts | 125 +- .../test/integration/change_detection_spec.ts | 81 +- .../integration/content_projection_spec.ts | 37 +- .../integration/downgrade_component_spec.ts | 556 +++---- .../test/integration/downgrade_module_spec.ts | 672 ++++---- .../static/test/integration/examples_spec.ts | 10 +- .../static/test/integration/injection_spec.ts | 52 +- .../test/integration/testability_spec.ts | 148 +- .../integration/upgrade_component_spec.ts | 1439 ++++++++--------- pnpm-lock.yaml | 82 +- tools/testing/zone_base_setup.mts | 1 - vscode-ng-language-service/package.json | 6 +- 39 files changed, 2961 insertions(+), 2780 deletions(-) create mode 100644 packages/core/test/debug/BUILD.bazel diff --git a/adev/package.json b/adev/package.json index cf0deb2bbf1..54bac83ad4d 100644 --- a/adev/package.json +++ b/adev/package.json @@ -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", diff --git a/adev/shared-docs/services/search-history.service.spec.ts b/adev/shared-docs/services/search-history.service.spec.ts index 3103797f6c3..28b30c07f5e 100644 --- a/adev/shared-docs/services/search-history.service.spec.ts +++ b/adev/shared-docs/services/search-history.service.spec.ts @@ -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; diff --git a/adev/src/app/features/references/pipes/api-label.pipe.spec.ts b/adev/src/app/features/references/pipes/api-label.pipe.spec.ts index 731ad01e75a..b4792b1f66e 100644 --- a/adev/src/app/features/references/pipes/api-label.pipe.spec.ts +++ b/adev/src/app/features/references/pipes/api-label.pipe.spec.ts @@ -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'); }); diff --git a/modules/package.json b/modules/package.json index 3ded88c6e3e..6e171dc82c4 100644 --- a/modules/package.json +++ b/modules/package.json @@ -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", diff --git a/ngp-vscode-ng-language-service/package.json b/ngp-vscode-ng-language-service/package.json index b037acd2354..af8a818e673 100644 --- a/ngp-vscode-ng-language-service/package.json +++ b/ngp-vscode-ng-language-service/package.json @@ -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", diff --git a/package.json b/package.json index 323c7a4ed54..e8401ac1a26 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/packages/animations/test/animation_group_player_spec.ts b/packages/animations/test/animation_group_player_spec.ts index e7a628d1978..03d9447aef4 100644 --- a/packages/animations/test/animation_group_player_spec.ts +++ b/packages/animations/test/animation_group_player_spec.ts @@ -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); - })); + }); }); diff --git a/packages/animations/test/animation_player_spec.ts b/packages/animations/test/animation_player_spec.ts index 08ad2644831..66159d5f2ee 100644 --- a/packages/animations/test/animation_player_spec.ts +++ b/packages/animations/test/animation_player_spec.ts @@ -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']); - })); + }); }); diff --git a/packages/animations/test/browser_animation_builder_spec.ts b/packages/animations/test/browser_animation_builder_spec.ts index c4b052cf536..4aae93adb4d 100644 --- a/packages/animations/test/browser_animation_builder_spec.ts +++ b/packages/animations/test/browser_animation_builder_spec.ts @@ -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(() => { diff --git a/packages/core/rxjs-interop/test/to_observable_spec.ts b/packages/core/rxjs-interop/test/to_observable_spec.ts index f4769614e81..ac374142995 100644 --- a/packages/core/rxjs-interop/test/to_observable_spec.ts +++ b/packages/core/rxjs-interop/test/to_observable_spec.ts @@ -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; let injector!: EnvironmentInjector; diff --git a/packages/core/test/acceptance/pipe_spec.ts b/packages/core/test/acceptance/pipe_spec.ts index 10ce1f2ef9e..ebf72124eee 100644 --- a/packages/core/test/acceptance/pipe_spec.ts +++ b/packages/core/test/acceptance/pipe_spec.ts @@ -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`, () => { diff --git a/packages/core/test/change_detection_scheduler_spec.ts b/packages/core/test/change_detection_scheduler_spec.ts index e761a72bf47..7aea9bb3669 100644 --- a/packages/core/test/change_detection_scheduler_spec.ts +++ b/packages/core/test/change_detection_scheduler_spec.ts @@ -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[] { diff --git a/packages/core/test/component_fixture_spec.ts b/packages/core/test/component_fixture_spec.ts index ad25b957542..40097a72f5c 100644 --- a/packages/core/test/component_fixture_spec.ts +++ b/packages/core/test/component_fixture_spec.ts @@ -32,6 +32,8 @@ import { withModule, } from '../testing'; +const {withProxyZone} = (Zone as any)[Zone.__symbol__('fakeAsyncTest')]; + @Component({ template: `Original {{ simpleBinding }}`, }) @@ -348,36 +350,41 @@ describe('ComponentFixture', () => { expect(() => fixture.detectChanges()).toThrow(); }); - it('should not duplicate errors when used with fake async', fakeAsync(() => { - @Component({ - template: '', - }) - 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: '', + }) + 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({ diff --git a/packages/core/test/debug/BUILD.bazel b/packages/core/test/debug/BUILD.bazel new file mode 100644 index 00000000000..bc28989500d --- /dev/null +++ b/packages/core/test/debug/BUILD.bazel @@ -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", + ], +) diff --git a/packages/core/test/debug/stability_debug_spec.ts b/packages/core/test/debug/stability_debug_spec.ts index 5d50d8859a3..b0b50dc45ed 100644 --- a/packages/core/test/debug/stability_debug_spec.ts +++ b/packages/core/test/debug/stability_debug_spec.ts @@ -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(); - })); + }); }); diff --git a/packages/core/test/fake_async_spec.ts b/packages/core/test/fake_async_spec.ts index 55aae31ca9c..b1d926e8968 100644 --- a/packages/core/test/fake_async_spec.ts +++ b/packages/core/test/fake_async_spec.ts @@ -11,360 +11,490 @@ import {Log} from '../testing/src/testing_internal'; import {EventManager} from '@angular/platform-browser'; const resolvedPromise = Promise.resolve(null); -const ProxyZoneSpec: {assertPresent: () => void} = (Zone as any)['ProxyZoneSpec']; +const ProxyZoneSpec: {new (): ZoneSpec; assertPresent: () => void} = (Zone as any)['ProxyZoneSpec']; +const proxyZone = Zone.root.fork(new ProxyZoneSpec()); +const withProxyZone = (fn: T): T => { + return function (this: unknown, ...args: unknown[]) { + return proxyZone.run(fn, this, args); + } as unknown as T; +}; describe('fake async', () => { - it('should run synchronous code', () => { - let ran = false; - fakeAsync(() => { - ran = true; - })(); - - expect(ran).toEqual(true); - }); - - it('should pass arguments to the wrapped function', () => { - fakeAsync((foo: string, bar: string) => { - expect(foo).toEqual('foo'); - expect(bar).toEqual('bar'); - })('foo', 'bar'); - }); - - it('should work with inject()', fakeAsync( - inject([EventManager], (eventManager: EventManager) => { - expect(eventManager).toBeInstanceOf(EventManager); - }), - )); - - it('should throw on nested calls', () => { - expect(() => { + it( + 'should run synchronous code', + withProxyZone(() => { + let ran = false; fakeAsync(() => { - fakeAsync((): null => null)(); + ran = true; })(); - }).toThrowError('fakeAsync() calls can not be nested'); - }); - it('should flush microtasks before returning', () => { - let thenRan = false; + expect(ran).toEqual(true); + }), + ); - fakeAsync(() => { - resolvedPromise.then((_) => { - thenRan = true; - }); - })(); + it( + 'should pass arguments to the wrapped function', + withProxyZone(() => { + fakeAsync((foo: string, bar: string) => { + expect(foo).toEqual('foo'); + expect(bar).toEqual('bar'); + })('foo', 'bar'); + }), + ); - expect(thenRan).toEqual(true); - }); + it( + 'should work with inject()', + withProxyZone( + fakeAsync( + inject([EventManager], (eventManager: EventManager) => { + expect(eventManager).toBeInstanceOf(EventManager); + }), + ), + ), + ); - it('should propagate the return value', () => { - expect(fakeAsync(() => 'foo')()).toEqual('foo'); - }); + it( + 'should throw on nested calls', + withProxyZone(() => { + expect(() => { + fakeAsync(() => { + fakeAsync((): null => null)(); + })(); + }).toThrowError('fakeAsync() calls can not be nested'); + }), + ); + + it( + 'should flush microtasks before returning', + withProxyZone(() => { + let thenRan = false; + + fakeAsync(() => { + resolvedPromise.then((_) => { + thenRan = true; + }); + })(); + + expect(thenRan).toEqual(true); + }), + ); + + it( + 'should propagate the return value', + withProxyZone(() => { + expect(fakeAsync(() => 'foo')()).toEqual('foo'); + }), + ); describe('Promise', () => { - it('should run asynchronous code', fakeAsync(() => { - let thenRan = false; - resolvedPromise.then((_) => { - thenRan = true; - }); - - expect(thenRan).toEqual(false); - - flushMicrotasks(); - expect(thenRan).toEqual(true); - })); - - it('should run chained thens', fakeAsync(() => { - const log = new Log(); - - resolvedPromise.then((_) => log.add(1)).then((_) => log.add(2)); - - expect(log.result()).toEqual(''); - - flushMicrotasks(); - expect(log.result()).toEqual('1; 2'); - })); - - it('should run Promise created in Promise', fakeAsync(() => { - const log = new Log(); - - resolvedPromise.then((_) => { - log.add(1); - resolvedPromise.then((_) => log.add(2)); - }); - - expect(log.result()).toEqual(''); - - flushMicrotasks(); - expect(log.result()).toEqual('1; 2'); - })); - - it('should complain if the test throws an exception during async calls', () => { - expect(() => { + it( + 'should run asynchronous code', + withProxyZone( fakeAsync(() => { + let thenRan = false; resolvedPromise.then((_) => { - throw new Error('async'); + thenRan = true; }); - flushMicrotasks(); - })(); - }).toThrow(); - }); - it('should complain if a test throws an exception', () => { - expect(() => { + expect(thenRan).toEqual(false); + + flushMicrotasks(); + expect(thenRan).toEqual(true); + }), + ), + ); + + it( + 'should run chained thens', + withProxyZone( fakeAsync(() => { - throw new Error('sync'); - })(); - }).toThrowError('sync'); - }); + const log = new Log(); + + resolvedPromise.then((_) => log.add(1)).then((_) => log.add(2)); + + expect(log.result()).toEqual(''); + + flushMicrotasks(); + expect(log.result()).toEqual('1; 2'); + }), + ), + ); + + it( + 'should run Promise created in Promise', + withProxyZone( + fakeAsync(() => { + const log = new Log(); + + resolvedPromise.then((_) => { + log.add(1); + resolvedPromise.then((_) => log.add(2)); + }); + + expect(log.result()).toEqual(''); + + flushMicrotasks(); + expect(log.result()).toEqual('1; 2'); + }), + ), + ); + + it( + 'should complain if the test throws an exception during async calls', + withProxyZone(() => { + expect(() => { + fakeAsync(() => { + resolvedPromise.then((_) => { + throw new Error('async'); + }); + flushMicrotasks(); + })(); + }).toThrow(); + }), + ); + + it( + 'should complain if a test throws an exception', + withProxyZone(() => { + expect(() => { + fakeAsync(() => { + throw new Error('sync'); + })(); + }).toThrowError('sync'); + }), + ); }); describe('timers', () => { - it('should run queued zero duration timer on zero tick', fakeAsync(() => { - let ran = false; - setTimeout(() => { - ran = true; - }, 0); + it( + 'should run queued zero duration timer on zero tick', + withProxyZone( + fakeAsync(() => { + let ran = false; + setTimeout(() => { + ran = true; + }, 0); - expect(ran).toEqual(false); + expect(ran).toEqual(false); - tick(); - expect(ran).toEqual(true); - })); + tick(); + expect(ran).toEqual(true); + }), + ), + ); - it('should run queued timer after sufficient clock ticks', fakeAsync(() => { - let ran = false; - setTimeout(() => { - ran = true; - }, 10); + it( + 'should run queued timer after sufficient clock ticks', + withProxyZone( + fakeAsync(() => { + let ran = false; + setTimeout(() => { + ran = true; + }, 10); - tick(6); - expect(ran).toEqual(false); + tick(6); + expect(ran).toEqual(false); - tick(6); - expect(ran).toEqual(true); - })); + tick(6); + expect(ran).toEqual(true); + }), + ), + ); - it('should run new macro tasks created by timer callback', fakeAsync(() => { - function nestedTimer(callback: () => any): void { - setTimeout(() => setTimeout(() => callback())); - } - const callback = jasmine.createSpy('callback'); - nestedTimer(callback); - expect(callback).not.toHaveBeenCalled(); - tick(0); - expect(callback).toHaveBeenCalled(); - })); + it( + 'should run new macro tasks created by timer callback', + withProxyZone( + fakeAsync(() => { + function nestedTimer(callback: () => any): void { + setTimeout(() => setTimeout(() => callback())); + } + const callback = jasmine.createSpy('callback'); + nestedTimer(callback); + expect(callback).not.toHaveBeenCalled(); + tick(0); + expect(callback).toHaveBeenCalled(); + }), + ), + ); - it('should not queue nested timer on tick with processNewMacroTasksSynchronously=false', fakeAsync(() => { - function nestedTimer(callback: () => any): void { - setTimeout(() => setTimeout(() => callback())); - } - const callback = jasmine.createSpy('callback'); - nestedTimer(callback); - expect(callback).not.toHaveBeenCalled(); - tick(0, {processNewMacroTasksSynchronously: false}); - expect(callback).not.toHaveBeenCalled(); - flush(); - expect(callback).toHaveBeenCalled(); - })); + it( + 'should not queue nested timer on tick with processNewMacroTasksSynchronously=false', + withProxyZone( + fakeAsync(() => { + function nestedTimer(callback: () => any): void { + setTimeout(() => setTimeout(() => callback())); + } + const callback = jasmine.createSpy('callback'); + nestedTimer(callback); + expect(callback).not.toHaveBeenCalled(); + tick(0, {processNewMacroTasksSynchronously: false}); + expect(callback).not.toHaveBeenCalled(); + flush(); + expect(callback).toHaveBeenCalled(); + }), + ), + ); - it('should run queued timer only once', fakeAsync(() => { - let cycles = 0; - setTimeout(() => { - cycles++; - }, 10); + it( + 'should run queued timer only once', + withProxyZone( + fakeAsync(() => { + let cycles = 0; + setTimeout(() => { + cycles++; + }, 10); - tick(10); - expect(cycles).toEqual(1); + tick(10); + expect(cycles).toEqual(1); - tick(10); - expect(cycles).toEqual(1); + tick(10); + expect(cycles).toEqual(1); - tick(10); - expect(cycles).toEqual(1); - })); + tick(10); + expect(cycles).toEqual(1); + }), + ), + ); - it('should not run cancelled timer', fakeAsync(() => { - let ran = false; - const id = setTimeout(() => { - ran = true; - }, 10); - clearTimeout(id); + it( + 'should not run cancelled timer', + withProxyZone( + fakeAsync(() => { + let ran = false; + const id = setTimeout(() => { + ran = true; + }, 10); + clearTimeout(id); - tick(10); - expect(ran).toEqual(false); - })); + tick(10); + expect(ran).toEqual(false); + }), + ), + ); - it('should throw an error on dangling timers', () => { - expect(() => { - fakeAsync( - () => { - setTimeout(() => {}, 10); - }, - {flush: false}, - )(); - }).toThrowError('1 timer(s) still in the queue.'); - }); + it( + 'should throw an error on dangling timers', + withProxyZone(() => { + expect(() => { + fakeAsync( + () => { + setTimeout(() => {}, 10); + }, + {flush: false}, + )(); + }).toThrowError('1 timer(s) still in the queue.'); + }), + ); - it('should throw an error on dangling periodic timers', () => { - expect(() => { - fakeAsync( - () => { - setInterval(() => {}, 10); - }, - {flush: false}, - )(); - }).toThrowError('1 periodic timer(s) still in the queue.'); - }); + it( + 'should throw an error on dangling periodic timers', + withProxyZone(() => { + expect(() => { + fakeAsync( + () => { + setInterval(() => {}, 10); + }, + {flush: false}, + )(); + }).toThrowError('1 periodic timer(s) still in the queue.'); + }), + ); - it('should run periodic timers', fakeAsync(() => { - let cycles = 0; - const id = setInterval(() => { - cycles++; - }, 10); + it( + 'should run periodic timers', + withProxyZone( + fakeAsync(() => { + let cycles = 0; + const id = setInterval(() => { + cycles++; + }, 10); - tick(10); - expect(cycles).toEqual(1); + tick(10); + expect(cycles).toEqual(1); - tick(10); - expect(cycles).toEqual(2); + tick(10); + expect(cycles).toEqual(2); - tick(10); - expect(cycles).toEqual(3); - clearInterval(id); - })); + tick(10); + expect(cycles).toEqual(3); + clearInterval(id); + }), + ), + ); - it('should not run cancelled periodic timer', fakeAsync(() => { - let ran = false; - const id = setInterval(() => { - ran = true; - }, 10); - clearInterval(id); + it( + 'should not run cancelled periodic timer', + withProxyZone( + fakeAsync(() => { + let ran = false; + const id = setInterval(() => { + ran = true; + }, 10); + clearInterval(id); - tick(10); - expect(ran).toEqual(false); - })); + tick(10); + expect(ran).toEqual(false); + }), + ), + ); - it('should be able to cancel periodic timers from a callback', fakeAsync(() => { - let cycles = 0; - const id = setInterval(() => { - cycles++; - clearInterval(id); - }, 10); + it( + 'should be able to cancel periodic timers from a callback', + withProxyZone( + fakeAsync(() => { + let cycles = 0; + const id = setInterval(() => { + cycles++; + clearInterval(id); + }, 10); - tick(10); - expect(cycles).toEqual(1); + tick(10); + expect(cycles).toEqual(1); - tick(10); - expect(cycles).toEqual(1); - })); + tick(10); + expect(cycles).toEqual(1); + }), + ), + ); - it('should clear periodic timers', fakeAsync(() => { - let cycles = 0; - setInterval(() => { - cycles++; - }, 10); + it( + 'should clear periodic timers', + withProxyZone( + fakeAsync(() => { + let cycles = 0; + setInterval(() => { + cycles++; + }, 10); - tick(10); - expect(cycles).toEqual(1); + tick(10); + expect(cycles).toEqual(1); - discardPeriodicTasks(); + discardPeriodicTasks(); - // Tick once to clear out the timer which already started. - tick(10); - expect(cycles).toEqual(2); + // Tick once to clear out the timer which already started. + tick(10); + expect(cycles).toEqual(2); - tick(10); - // Nothing should change - expect(cycles).toEqual(2); - })); + tick(10); + // Nothing should change + expect(cycles).toEqual(2); + }), + ), + ); - it('should process microtasks before timers', fakeAsync(() => { - const log = new Log(); + it( + 'should process microtasks before timers', + withProxyZone( + fakeAsync(() => { + const log = new Log(); - resolvedPromise.then((_) => log.add('microtask')); + resolvedPromise.then((_) => log.add('microtask')); - setTimeout(() => log.add('timer'), 9); + setTimeout(() => log.add('timer'), 9); - const id = setInterval(() => log.add('periodic timer'), 10); + const id = setInterval(() => log.add('periodic timer'), 10); - expect(log.result()).toEqual(''); + expect(log.result()).toEqual(''); - tick(10); - expect(log.result()).toEqual('microtask; timer; periodic timer'); - clearInterval(id); - })); + tick(10); + expect(log.result()).toEqual('microtask; timer; periodic timer'); + clearInterval(id); + }), + ), + ); - it('should process micro-tasks created in timers before next timers', fakeAsync(() => { - const log = new Log(); + it( + 'should process micro-tasks created in timers before next timers', + withProxyZone( + fakeAsync(() => { + const log = new Log(); - resolvedPromise.then((_) => log.add('microtask')); + resolvedPromise.then((_) => log.add('microtask')); - setTimeout(() => { - log.add('timer'); - resolvedPromise.then((_) => log.add('t microtask')); - }, 9); + setTimeout(() => { + log.add('timer'); + resolvedPromise.then((_) => log.add('t microtask')); + }, 9); - const id = setInterval(() => { - log.add('periodic timer'); - resolvedPromise.then((_) => log.add('pt microtask')); - }, 10); + const id = setInterval(() => { + log.add('periodic timer'); + resolvedPromise.then((_) => log.add('pt microtask')); + }, 10); - tick(10); - expect(log.result()).toEqual('microtask; timer; t microtask; periodic timer; pt microtask'); + tick(10); + expect(log.result()).toEqual( + 'microtask; timer; t microtask; periodic timer; pt microtask', + ); - tick(10); - expect(log.result()).toEqual( - 'microtask; timer; t microtask; periodic timer; pt microtask; periodic timer; pt microtask', - ); - clearInterval(id); - })); + tick(10); + expect(log.result()).toEqual( + 'microtask; timer; t microtask; periodic timer; pt microtask; periodic timer; pt microtask', + ); + clearInterval(id); + }), + ), + ); - it('should flush tasks', fakeAsync(() => { - let ran = false; - setTimeout(() => { - ran = true; - }, 10); + it( + 'should flush tasks', + withProxyZone( + fakeAsync(() => { + let ran = false; + setTimeout(() => { + ran = true; + }, 10); - flush(); - expect(ran).toEqual(true); - })); + flush(); + expect(ran).toEqual(true); + }), + ), + ); - it('should flush multiple tasks', fakeAsync(() => { - let ran = false; - let ran2 = false; - setTimeout(() => { - ran = true; - }, 10); - setTimeout(() => { - ran2 = true; - }, 30); + it( + 'should flush multiple tasks', + withProxyZone( + fakeAsync(() => { + let ran = false; + let ran2 = false; + setTimeout(() => { + ran = true; + }, 10); + setTimeout(() => { + ran2 = true; + }, 30); - let elapsed = flush(); + let elapsed = flush(); - expect(ran).toEqual(true); - expect(ran2).toEqual(true); - expect(elapsed).toEqual(30); - })); + expect(ran).toEqual(true); + expect(ran2).toEqual(true); + expect(elapsed).toEqual(30); + }), + ), + ); - it('should move periodic tasks', fakeAsync(() => { - let ran = false; - let count = 0; - setInterval(() => { - count++; - }, 10); - setTimeout(() => { - ran = true; - }, 35); + it( + 'should move periodic tasks', + withProxyZone( + fakeAsync(() => { + let ran = false; + let count = 0; + setInterval(() => { + count++; + }, 10); + setTimeout(() => { + ran = true; + }, 35); - let elapsed = flush(); + let elapsed = flush(); - expect(count).toEqual(3); - expect(ran).toEqual(true); - expect(elapsed).toEqual(35); + expect(count).toEqual(3); + expect(ran).toEqual(true); + expect(elapsed).toEqual(35); - discardPeriodicTasks(); - })); + discardPeriodicTasks(); + }), + ), + ); }); describe('outside of the fakeAsync zone', () => { @@ -396,38 +526,54 @@ describe('fake async', () => { describe('only one `fakeAsync` zone per test', () => { let zoneInBeforeEach: Zone; let zoneInTest1: Zone; - beforeEach(fakeAsync(() => { - zoneInBeforeEach = Zone.current; - })); + beforeEach( + withProxyZone( + fakeAsync(() => { + zoneInBeforeEach = Zone.current; + }), + ), + ); - it('should use the same zone as in beforeEach', fakeAsync(() => { - zoneInTest1 = Zone.current; - expect(zoneInTest1).toBe(zoneInBeforeEach); - })); + it( + 'should use the same zone as in beforeEach', + withProxyZone( + fakeAsync(() => { + zoneInTest1 = Zone.current; + expect(zoneInTest1).toBe(zoneInBeforeEach); + }), + ), + ); }); }); describe('ProxyZone', () => { - beforeEach(() => { - ProxyZoneSpec.assertPresent(); - }); + beforeEach( + withProxyZone(() => { + ProxyZoneSpec.assertPresent(); + }), + ); - afterEach(() => { - ProxyZoneSpec.assertPresent(); - }); + afterEach( + withProxyZone(() => { + ProxyZoneSpec.assertPresent(); + }), + ); - it('should allow fakeAsync zone to retroactively set a zoneSpec outside of fakeAsync', () => { - ProxyZoneSpec.assertPresent(); - let state: string = 'not run'; - const testZone = Zone.current.fork({name: 'test-zone'}); - fakeAsync(() => { - testZone.run(() => { - Promise.resolve('works').then((v) => (state = v)); - expect(state).toEqual('not run'); - flushMicrotasks(); - expect(state).toEqual('works'); - }); - })(); - expect(state).toEqual('works'); - }); + it( + 'should allow fakeAsync zone to retroactively set a zoneSpec outside of fakeAsync', + withProxyZone(() => { + ProxyZoneSpec.assertPresent(); + let state: string = 'not run'; + const testZone = Zone.current.fork({name: 'test-zone'}); + fakeAsync(() => { + testZone.run(() => { + Promise.resolve('works').then((v) => (state = v)); + expect(state).toEqual('not run'); + flushMicrotasks(); + expect(state).toEqual('works'); + }); + })(); + expect(state).toEqual('works'); + }), + ); }); diff --git a/packages/core/test/legacy_animation/legacy_animation_integration_spec.ts b/packages/core/test/legacy_animation/legacy_animation_integration_spec.ts index 6e34131f547..9fa75d5242e 100644 --- a/packages/core/test/legacy_animation/legacy_animation_integration_spec.ts +++ b/packages/core/test/legacy_animation/legacy_animation_integration_spec.ts @@ -45,7 +45,7 @@ import { ViewChild, ViewContainerRef, } from '../../src/core'; -import {fakeAsync, flushMicrotasks, TestBed} from '../../testing'; +import {TestBed} from '../../testing'; const DEFAULT_NAMESPACE_ID = 'id'; const DEFAULT_COMPONENT_ID = '1'; @@ -121,7 +121,7 @@ const DEFAULT_COMPONENT_ID = '1'; } describe('fakeAsync testing', () => { - it('should only require one flushMicrotasks call to kick off animation callbacks', fakeAsync(() => { + it('should only require one flushMicrotasks call to kick off animation callbacks', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'cmp', @@ -154,7 +154,7 @@ const DEFAULT_COMPONENT_ID = '1'; fixture.detectChanges(); expect(cmp.status).toEqual(''); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.status).toEqual('start'); let player = MockAnimationDriver.log.pop()!; @@ -169,11 +169,11 @@ const DEFAULT_COMPONENT_ID = '1'; player = MockAnimationDriver.log.pop()!; player.finish(); expect(cmp.status).toEqual(''); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.status).toEqual('done'); - })); + }); - it('should always run .start callbacks before .done callbacks even for noop animations', fakeAsync(() => { + it('should always run .start callbacks before .done callbacks even for noop animations', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'cmp', @@ -202,11 +202,11 @@ const DEFAULT_COMPONENT_ID = '1'; fixture.detectChanges(); expect(cmp.log).toEqual([]); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['start', 'done']); - })); + }); - it('should emit the correct totalTime value for a noop-animation', fakeAsync(() => { + it('should emit the correct totalTime value for a noop-animation', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'cmp', @@ -241,17 +241,17 @@ const DEFAULT_COMPONENT_ID = '1'; fixture.detectChanges(); expect(cmp.log).toEqual([]); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log.length).toEqual(2); const [start, end] = cmp.log; expect(start.totalTime).toEqual(1000); expect(end.totalTime).toEqual(1000); - })); + }); }); describe('component fixture integration', () => { describe('whenRenderingDone', () => { - it('should wait until the animations are finished until continuing', fakeAsync(() => { + it('should wait until the animations are finished until continuing', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'cmp', @@ -284,11 +284,11 @@ const DEFAULT_COMPONENT_ID = '1'; players[0].finish(); expect(isDone).toBe(false); - flushMicrotasks(); + await Promise.resolve(); expect(isDone).toBe(true); - })); + }); - it('should wait for a noop animation to finish before continuing', fakeAsync(() => { + it('should wait for a noop animation to finish before continuing', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'cmp', @@ -320,11 +320,11 @@ const DEFAULT_COMPONENT_ID = '1'; engine.flush(); expect(isDone).toBe(false); - flushMicrotasks(); + await Promise.resolve(); expect(isDone).toBe(true); - })); + }); - it('should wait for active animations to finish even if they have already started', fakeAsync(() => { + it('should wait for active animations to finish even if they have already started', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'cmp', @@ -351,13 +351,13 @@ const DEFAULT_COMPONENT_ID = '1'; let isDone = false; fixture.whenRenderingDone().then(() => (isDone = true)); - flushMicrotasks(); + await Promise.resolve(); expect(isDone).toBe(false); players[0].finish(); - flushMicrotasks(); + await Promise.resolve(); expect(isDone).toBe(true); - })); + }); }); }); @@ -576,7 +576,7 @@ const DEFAULT_COMPONENT_ID = '1'; expect(player.duration).toEqual(1234); }); - it('should always cancel the previous transition if a follow-up transition is not matched', fakeAsync(() => { + it('should always cancel the previous transition if a follow-up transition is not matched', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'if-cmp', @@ -623,7 +623,7 @@ const DEFAULT_COMPONENT_ID = '1'; expect(getLog().length).toEqual(0); expect(engine.players.length).toEqual(0); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.startEvent.toState).toEqual('a'); expect(cmp.startEvent.totalTime).toEqual(0); expect(cmp.startEvent.toState).toEqual('a'); @@ -638,7 +638,7 @@ const DEFAULT_COMPONENT_ID = '1'; expect(players.length).toEqual(1); expect(engine.players.length).toEqual(1); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.startEvent.toState).toEqual('b'); expect(cmp.startEvent.totalTime).toEqual(500); expect(cmp.startEvent.toState).toEqual('b'); @@ -655,16 +655,16 @@ const DEFAULT_COMPONENT_ID = '1'; expect(engine.players.length).toEqual(0); expect(getLog().length).toEqual(0); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.startEvent.toState).toEqual('c'); expect(cmp.startEvent.totalTime).toEqual(0); expect(cmp.startEvent.toState).toEqual('c'); expect(cmp.startEvent.totalTime).toEqual(0); expect(completed).toBe(true); - })); + }); - it('should always fire inner callbacks even if no animation is fired when a view is inserted', fakeAsync(() => { + it('should always fire inner callbacks even if no animation is fired when a view is inserted', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'if-cmp', @@ -694,16 +694,16 @@ const DEFAULT_COMPONENT_ID = '1'; const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual([]); cmp.exp = true; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['myAnimation-start', 'myAnimation-done']); - })); + }); it('should only turn a view removal as into `void` state transition', () => { @Component({ @@ -1017,7 +1017,7 @@ const DEFAULT_COMPONENT_ID = '1'; }); describe('host bindings', () => { - it('should trigger a state change animation from state => state on the component host element', fakeAsync(() => { + it('should trigger a state change animation from state => state on the component host element', () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'my-cmp', @@ -1062,9 +1062,9 @@ const DEFAULT_COMPONENT_ID = '1'; ['opacity', '1'], ]), ]); - })); + }); - it('should trigger a leave animation when the inner has ViewContainerRef injected', fakeAsync(() => { + it('should trigger a leave animation when the inner has ViewContainerRef injected', () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'parent-cmp', @@ -1121,9 +1121,9 @@ const DEFAULT_COMPONENT_ID = '1'; player.finish(); expect(fixture.debugElement.nativeElement.children.length).toBe(0); - })); + }); - it('should trigger a leave animation when the inner components host binding updates', fakeAsync(() => { + it('should trigger a leave animation when the inner components host binding updates', () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'parent-cmp', @@ -1179,9 +1179,9 @@ const DEFAULT_COMPONENT_ID = '1'; player.finish(); expect(fixture.debugElement.nativeElement.children.length).toBe(0); - })); + }); - it('should wait for child animations before removing parent', fakeAsync(() => { + it('should wait for child animations before removing parent', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, template: '', @@ -1237,12 +1237,12 @@ const DEFAULT_COMPONENT_ID = '1'; ]); player.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(fixture.nativeElement.children.length).toBe(0); - })); + }); // animationRenderer => nonAnimationRenderer - it('should trigger a leave animation when the outer components element binding updates on the host component element', fakeAsync(() => { + it('should trigger a leave animation when the outer components element binding updates on the host component element', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'parent-cmp', @@ -1295,11 +1295,11 @@ const DEFAULT_COMPONENT_ID = '1'; ]); player.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(fixture.debugElement.nativeElement.children.length).toBe(0); - })); + }); - it('should trigger a leave animation when both the inner and outer components trigger on the same element', fakeAsync(() => { + it('should trigger a leave animation when both the inner and outer components trigger on the same element', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'parent-cmp', @@ -1377,11 +1377,11 @@ const DEFAULT_COMPONENT_ID = '1'; p1.finish(); p2.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(fixture.debugElement.nativeElement.children.length).toBe(0); - })); + }); - it('should not throw when the host element is removed and no animation triggers', fakeAsync(() => { + it('should not throw when the host element is removed and no animation triggers', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'parent-cmp', @@ -1417,15 +1417,15 @@ const DEFAULT_COMPONENT_ID = '1'; cmp.exp = false; fixture.detectChanges(); engine.flush(); - flushMicrotasks(); + await Promise.resolve(); expect(getLog().length).toEqual(0); expect(fixture.debugElement.nativeElement.children.length).toBe(0); - flushMicrotasks(); + await Promise.resolve(); expect(fixture.debugElement.nativeElement.children.length).toBe(0); - })); + }); - it('should properly evaluate pre/auto-style values when components are inserted/removed which contain host animations', fakeAsync(() => { + it('should properly evaluate pre/auto-style values when components are inserted/removed which contain host animations', () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'parent-cmp', @@ -1465,7 +1465,7 @@ const DEFAULT_COMPONENT_ID = '1'; const item = items[i]; expect(item.style['display']).toBeFalsy(); } - })); + }); }); it('should cancel and merge in mid-animation styles into the follow-up animation, but only for animation keyframes that start right away', () => { @@ -1930,7 +1930,7 @@ const DEFAULT_COMPONENT_ID = '1'; } }); - it('should keep/restore the trigger value when there are move operations (with *ngFor + trackBy)', fakeAsync(() => { + it('should keep/restore the trigger value when there are move operations (with *ngFor + trackBy)', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'ani-cmp', @@ -1977,15 +1977,15 @@ const DEFAULT_COMPONENT_ID = '1'; const cmp = fixture.componentInstance; fixture.detectChanges(); - const completeAnimations = () => { + const completeAnimations = async () => { fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); engine.players.forEach((player) => player.finish()); }; cmp.log = []; [0, 1, 2].forEach(() => cmp.addItem()); - completeAnimations(); + await completeAnimations(); expect(cmp.log).toEqual([ '[item0] void => null', '[item1] void => null', @@ -1993,17 +1993,17 @@ const DEFAULT_COMPONENT_ID = '1'; ]); cmp.reverseItems(); - completeAnimations(); + await completeAnimations(); cmp.log = []; [0, 1, 2].forEach(() => cmp.removeItem()); - completeAnimations(); + await completeAnimations(); expect(cmp.log).toEqual([ '[item2] null => void', '[item1] null => void', '[item0] null => void', ]); - })); + }); it('should animate removals of nodes to the `void` state for each animation trigger, but treat all auto styles as pre styles', () => { @Component({ @@ -2467,7 +2467,7 @@ const DEFAULT_COMPONENT_ID = '1'; expect(players.length).toEqual(0); }); - it("should update the final state styles when params update even if the expression hasn't changed", fakeAsync(() => { + it("should update the final state styles when params update even if the expression hasn't changed", async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'ani-cmp', @@ -2498,7 +2498,7 @@ const DEFAULT_COMPONENT_ID = '1'; const element = player.element; player.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(hasStyle(element, 'color', 'red')).toBeTruthy(); cmp.exp = '1'; @@ -2506,7 +2506,7 @@ const DEFAULT_COMPONENT_ID = '1'; fixture.detectChanges(); resetLog(); - flushMicrotasks(); + await Promise.resolve(); expect(hasStyle(element, 'color', 'blue')).toBeTruthy(); cmp.exp = '1'; @@ -2514,9 +2514,9 @@ const DEFAULT_COMPONENT_ID = '1'; fixture.detectChanges(); resetLog(); - flushMicrotasks(); + await Promise.resolve(); expect(hasStyle(element, 'color', 'black')).toBeTruthy(); - })); + }); it('should substitute in values if the provided state match is an object with values', () => { @Component({ @@ -2565,7 +2565,7 @@ const DEFAULT_COMPONENT_ID = '1'; ]); }); - it('should retain substituted styles on the element once the animation is complete if referenced in the final state', fakeAsync(() => { + it('should retain substituted styles on the element once the animation is complete if referenced in the final state', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'ani-cmp', @@ -2632,14 +2632,14 @@ const DEFAULT_COMPONENT_ID = '1'; const element = p1.element; p1.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(hasStyle(element, 'color', 'blue')).toBeTruthy(); expect(hasStyle(element, 'fontSize', '50px')).toBeTruthy(); expect(hasStyle(element, 'width', '888px')).toBeTruthy(); - })); + }); - it('should only evaluate final state param substitutions from the expression and state values and not from the transition options ', fakeAsync(() => { + it('should only evaluate final state param substitutions from the expression and state values and not from the transition options ', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'ani-cmp', @@ -2705,11 +2705,11 @@ const DEFAULT_COMPONENT_ID = '1'; const element = p1.element; p1.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(hasStyle(element, 'width', '100px')).toBeTruthy(); expect(hasStyle(element, 'height', '100px')).toBeTruthy(); - })); + }); it('should apply default params when resolved animation value is null or undefined', () => { @Component({ @@ -2988,7 +2988,7 @@ const DEFAULT_COMPONENT_ID = '1'; }); describe('animation listeners', () => { - it('should trigger a `start` state change listener for when the animation changes state from void => state', fakeAsync(() => { + it('should trigger a `start` state change listener for when the animation changes state from void => state', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'if-cmp', @@ -3021,16 +3021,16 @@ const DEFAULT_COMPONENT_ID = '1'; const cmp = fixture.componentInstance; cmp.exp = 'true'; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.event?.triggerName).toEqual('myAnimation'); expect(cmp.event?.phaseName).toEqual('start'); expect(cmp.event?.totalTime).toEqual(500); expect(cmp.event?.fromState).toEqual('void'); expect(cmp.event?.toState).toEqual('true'); - })); + }); - it('should trigger a `done` state change listener for when the animation changes state from a => b', fakeAsync(() => { + it('should trigger a `done` state change listener for when the animation changes state from a => b', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'if-cmp', @@ -3074,16 +3074,16 @@ const DEFAULT_COMPONENT_ID = '1'; const player = engine.players.pop()!; player.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.event?.triggerName).toEqual('myAnimation123'); expect(cmp.event?.phaseName).toEqual('done'); expect(cmp.event?.totalTime).toEqual(999); expect(cmp.event?.fromState).toEqual('void'); expect(cmp.event?.toState).toEqual('b'); - })); + }); - it('should handle callbacks for multiple triggers running simultaneously', fakeAsync(() => { + it('should handle callbacks for multiple triggers running simultaneously', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'if-cmp', @@ -3142,12 +3142,12 @@ const DEFAULT_COMPONENT_ID = '1'; expect(cmp.event1).toBeFalsy(); expect(cmp.event2).toBeFalsy(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.event1?.triggerName).toBeTruthy('ani1'); expect(cmp.event2?.triggerName).toBeTruthy('ani2'); - })); + }); - it('should handle callbacks for multiple triggers running simultaneously on the same element', fakeAsync(() => { + it('should handle callbacks for multiple triggers running simultaneously on the same element', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'if-cmp', @@ -3210,12 +3210,12 @@ const DEFAULT_COMPONENT_ID = '1'; expect(cmp.event1).toBeFalsy(); expect(cmp.event2).toBeFalsy(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.event1?.triggerName).toBeTruthy('ani1'); expect(cmp.event2?.triggerName).toBeTruthy('ani2'); - })); + }); - it('should handle a leave animation for multiple triggers even if not all triggers have their own leave transition specified', fakeAsync(() => { + it('should handle a leave animation for multiple triggers even if not all triggers have their own leave transition specified', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'if-cmp', @@ -3244,7 +3244,7 @@ const DEFAULT_COMPONENT_ID = '1'; expect(players.length).toEqual(1); let [p1] = players; p1.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(elm.innerText.trim()).toEqual('123'); resetLog(); @@ -3255,11 +3255,11 @@ const DEFAULT_COMPONENT_ID = '1'; expect(players.length).toEqual(1); [p1] = players; p1.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(elm.innerText.trim()).toEqual(''); - })); + }); - it('should trigger a state change listener for when the animation changes state from void => state on the host element', fakeAsync(() => { + it('should trigger a state change listener for when the animation changes state from void => state on the host element', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'my-cmp', @@ -3292,16 +3292,16 @@ const DEFAULT_COMPONENT_ID = '1'; const cmp = fixture.componentInstance; cmp.exp = 'TRUE'; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.event?.triggerName).toEqual('myAnimation2'); expect(cmp.event?.phaseName).toEqual('start'); expect(cmp.event?.totalTime).toEqual(1000); expect(cmp.event?.fromState).toEqual('void'); expect(cmp.event?.toState).toEqual('TRUE'); - })); + }); - it('should always fire callbacks even when a transition is not detected', fakeAsync(() => { + it('should always fire callbacks even when a transition is not detected', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'my-cmp', @@ -3331,18 +3331,18 @@ const DEFAULT_COMPONENT_ID = '1'; cmp.exp = 'a'; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['start => a', 'done => a']); cmp.log = []; cmp.exp = 'b'; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['start => b', 'done => b']); - })); + }); - it('should fire callback events for leave animations even if there is no leave transition', fakeAsync(() => { + it('should fire callback events for leave animations even if there is no leave transition', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'my-cmp', @@ -3376,19 +3376,19 @@ const DEFAULT_COMPONENT_ID = '1'; cmp.exp = true; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['start => _default_', 'done => _default_']); cmp.log = []; cmp.exp = false; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['start => void', 'done => void']); - })); + }); - it('should fire callbacks on a sub animation once it starts and finishes', fakeAsync(() => { + it('should fire callbacks on a sub animation once it starts and finishes', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'my-cmp', @@ -3444,7 +3444,7 @@ const DEFAULT_COMPONENT_ID = '1'; cmp.exp2 = 'go'; fixture.detectChanges(); engine.flush(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['parent-start', 'child-start']); cmp.log = []; @@ -3461,19 +3461,19 @@ const DEFAULT_COMPONENT_ID = '1'; const [_scp, pp1, pcp, pp2] = players; pp1.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual([]); pcp.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual([]); pp2.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['parent-done', 'child-done']); - })); + }); - it('should fire callbacks and collect the correct the totalTime and element details for any queried sub animations', fakeAsync(() => { + it('should fire callbacks and collect the correct the totalTime and element details for any queried sub animations', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'my-cmp', @@ -3525,7 +3525,7 @@ const DEFAULT_COMPONENT_ID = '1'; cmp.exp = 'go'; fixture.detectChanges(); engine.flush(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['c-0-start', 'c-1-start', 'c-2-start', 'c-3-start']); cmp.log = []; @@ -3562,14 +3562,14 @@ const DEFAULT_COMPONENT_ID = '1'; pc2p1.finish(); pc3p1.finish(); pc4p1.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual([]); pc1p2.finish(); pc2p2.finish(); pc3p2.finish(); pc4p2.finish(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.log).toEqual(['all-done', 'c-0-done', 'c-1-done', 'c-2-done', 'c-3-done']); @@ -3583,7 +3583,7 @@ const DEFAULT_COMPONENT_ID = '1'; expect(cmp.events['c-2'].element.innerText.trim()).toEqual('2'); expect(cmp.events['c-3'].totalTime).toEqual(1500); expect(cmp.events['c-3'].element.innerText.trim()).toEqual('3'); - })); + }); }); describe('animation control flags', () => { @@ -3826,7 +3826,7 @@ const DEFAULT_COMPONENT_ID = '1'; expect(parent.childElementCount).toEqual(0); }); - it('should properly resolve animation event listeners when disabled', fakeAsync(() => { + it('should properly resolve animation event listeners when disabled', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'if-cmp', @@ -3868,7 +3868,7 @@ const DEFAULT_COMPONENT_ID = '1'; cmp.exp = '1'; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.startEvent?.totalTime).toEqual(9876); expect(cmp.startEvent?.disabled).toBeTruthy(); expect(cmp.doneEvent?.totalTime).toEqual(9876); @@ -3877,11 +3877,11 @@ const DEFAULT_COMPONENT_ID = '1'; cmp.exp = '2'; cmp.disableExp = false; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); expect(cmp.startEvent?.totalTime).toEqual(9876); expect(cmp.startEvent?.disabled).toBeFalsy(); // the done event isn't fired because it's an actual animation - })); + }); it('should work when there are no animations on the component handling the disable/enable flag', () => { @Component({ @@ -3970,7 +3970,7 @@ const DEFAULT_COMPONENT_ID = '1'; expect(getLog().length).toEqual(0); }); - it('should respect parent/sub animations when the respective area in the DOM is disabled', fakeAsync(() => { + it('should respect parent/sub animations when the respective area in the DOM is disabled', async () => { @Component({ changeDetection: ChangeDetectionStrategy.Eager, selector: 'parent-cmp', @@ -4018,19 +4018,19 @@ const DEFAULT_COMPONENT_ID = '1'; cmp.disableExp = true; cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); cmp.exp = 'empty'; cmp.items = []; cmp.doneLog = []; fixture.detectChanges(); - flushMicrotasks(); + await Promise.resolve(); const elms = cmp.container.nativeElement.querySelectorAll('.item'); expect(elms.length).toEqual(0); expect(cmp.doneLog.length).toEqual(6); - })); + }); }); }); diff --git a/packages/core/test/legacy_animation/legacy_animation_query_integration_spec.ts b/packages/core/test/legacy_animation/legacy_animation_query_integration_spec.ts index a03eecb2958..f392e6885b3 100644 --- a/packages/core/test/legacy_animation/legacy_animation_query_integration_spec.ts +++ b/packages/core/test/legacy_animation/legacy_animation_query_integration_spec.ts @@ -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({ diff --git a/packages/core/test/legacy_animation/legacy_animation_router_integration_spec.ts b/packages/core/test/legacy_animation/legacy_animation_router_integration_spec.ts index 31cd43a9931..7d39e3052f4 100644 --- a/packages/core/test/legacy_animation/legacy_animation_router_integration_spec.ts +++ b/packages/core/test/legacy_animation/legacy_animation_router_integration_spec.ts @@ -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: '', @@ -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'); - })); + }); }); }); diff --git a/packages/core/test/testability/testability_spec.ts b/packages/core/test/testability/testability_spec.ts index 547f7ef134f..a2e0d2c1bc1 100644 --- a/packages/core/test/testability/testability_spec.ts +++ b/packages/core/test/testability/testability_spec.ts @@ -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((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(); - })); + }); }); diff --git a/packages/core/test/zone/ng_zone_spec.ts b/packages/core/test/zone/ng_zone_spec.ts index f7b4823c0f8..6bea22d4bed 100644 --- a/packages/core/test/zone/ng_zone_spec.ts +++ b/packages/core/test/zone/ng_zone_spec.ts @@ -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((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', () => { diff --git a/packages/examples/core/testing/ts/example_spec.ts b/packages/examples/core/testing/ts/example_spec.ts index 9240d39622e..5ba0b916f04 100644 --- a/packages/examples/core/testing/ts/example_spec.ts +++ b/packages/examples/core/testing/ts/example_spec.ts @@ -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'); diff --git a/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts b/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts index 4453a438437..72601927750 100644 --- a/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts +++ b/packages/misc/angular-in-memory-web-api/test/http-client-backend-service_spec.ts @@ -22,9 +22,9 @@ import { withFetch, } from '@angular/common/http'; import {importProvidersFrom, Injectable} from '@angular/core'; -import {TestBed, waitForAsync} from '@angular/core/testing'; +import {TestBed} from '@angular/core/testing'; import {HttpClientBackendService, HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api'; -import {Observable, of, zip} from 'rxjs'; +import {firstValueFrom, Observable, of, zip} from 'rxjs'; import {concatMap, map, tap} from 'rxjs/operators'; import {Hero} from './fixtures/hero'; @@ -50,16 +50,12 @@ describe('HttpClient Backend Service', () => { http = TestBed.inject(HttpClient); }); - it('can get heroes', waitForAsync(() => { - http - .get('api/heroes') - .subscribe( - (heroes) => expect(heroes.length).toBeGreaterThan(0, 'should have heroes'), - failRequest, - ); - })); + it('can get heroes', async () => { + const heroes = await firstValueFrom(http.get('api/heroes')); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }); - it('GET should be a "cold" observable', waitForAsync(() => { + it('GET should be a "cold" observable', async () => { const httpBackend = TestBed.inject(HttpBackend); const spy = spyOn(httpBackend, 'collectionHandler').and.callThrough(); const get$ = http.get('api/heroes'); @@ -67,25 +63,29 @@ describe('HttpClient Backend Service', () => { // spy on `collectionHandler` should not be called before subscribe expect(spy).not.toHaveBeenCalled(); - get$.subscribe((heroes) => { - expect(spy).toHaveBeenCalled(); - expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); - }, failRequest); - })); + const heroes = await firstValueFrom(get$); + expect(spy).toHaveBeenCalled(); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }); - it('GET should wait until after delay to respond', waitForAsync(() => { + it('GET should wait until after delay to respond', async () => { // to make test fail, set `delay=0` above let gotResponse = false; - http.get('api/heroes').subscribe((heroes) => { - gotResponse = true; - expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); - }, failRequest); + const p = firstValueFrom( + http.get('api/heroes').pipe( + tap((heroes) => { + gotResponse = true; + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }), + ), + ); expect(gotResponse).toBe(false, 'should delay before response'); - })); + await p; + }); - it('Should only initialize the db once', waitForAsync(() => { + it('Should only initialize the db once', async () => { const httpBackend = TestBed.inject(HttpBackend); const spy = spyOn(httpBackend, 'resetDb').and.callThrough(); @@ -93,127 +93,120 @@ describe('HttpClient Backend Service', () => { // Only the first should initialize by calling `resetDb` // All should wait until the db is "ready" // then they share the same db instance. - http.get('api/heroes').subscribe(); - http.get('api/heroes').subscribe(); - http.get('api/heroes').subscribe(); - http.get('api/heroes').subscribe(); + const p1 = firstValueFrom(http.get('api/heroes')); + const p2 = firstValueFrom(http.get('api/heroes')); + const p3 = firstValueFrom(http.get('api/heroes')); + const p4 = firstValueFrom(http.get('api/heroes')); expect(spy.calls.count()).toBe(1); - })); + await Promise.all([p1, p2, p3, p4]); + }); - it('can get heroes (w/ a different base path)', waitForAsync(() => { - http.get('some-base-path/heroes').subscribe((heroes) => { - expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); - }, failRequest); - })); + it('can get heroes (w/ a different base path)', async () => { + const heroes = await firstValueFrom(http.get('some-base-path/heroes')); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }); - it('should 404 when GET unknown collection (after delay)', waitForAsync(() => { + it('should 404 when GET unknown collection (after delay)', async () => { let gotError = false; const url = 'api/unknown-collection'; - http.get(url).subscribe( - () => fail(`should not have found data for '${url}'`), - (err) => { - gotError = true; - expect(err.status).toBe(404, 'should have 404 status'); - }, - ); + const p = new Promise((resolve) => { + http.get(url).subscribe( + () => { + fail(`should not have found data for '${url}'`); + resolve(); + }, + (err) => { + gotError = true; + expect(err.status).toBe(404, 'should have 404 status'); + resolve(); + }, + ); + }); expect(gotError).toBe(false, 'should not get error until after delay'); - })); + await p; + }); - it('should return the hero w/id=1 for GET app/heroes/1', waitForAsync(() => { - http - .get('api/heroes/1') - .subscribe((hero) => expect(hero).toBeDefined('should find hero with id=1'), failRequest); - })); + it('should return the hero w/id=1 for GET app/heroes/1', async () => { + const hero = await firstValueFrom(http.get('api/heroes/1')); + expect(hero).toBeDefined('should find hero with id=1'); + }); // test where id is string that looks like a number - it('should return the stringer w/id="10" for GET app/stringers/10', waitForAsync(() => { - http - .get('api/stringers/10') - .subscribe( - (hero) => expect(hero).toBeDefined('should find string with id="10"'), - failRequest, - ); - })); + it('should return the stringer w/id="10" for GET app/stringers/10', async () => { + const hero = await firstValueFrom(http.get('api/stringers/10')); + expect(hero).toBeDefined('should find string with id="10"'); + }); - it('should return 1-item array for GET app/heroes/?id=1', waitForAsync(() => { - http - .get('api/heroes/?id=1') - .subscribe( - (heroes) => expect(heroes.length).toBe(1, 'should find one hero w/id=1'), - failRequest, - ); - })); + it('should return 1-item array for GET app/heroes/?id=1', async () => { + const heroes = await firstValueFrom(http.get('api/heroes/?id=1')); + expect(heroes.length).toBe(1, 'should find one hero w/id=1'); + }); - it('should return 1-item array for GET app/heroes?id=1', waitForAsync(() => { - http - .get('api/heroes?id=1') - .subscribe( - (heroes) => expect(heroes.length).toBe(1, 'should find one hero w/id=1'), - failRequest, - ); - })); + it('should return 1-item array for GET app/heroes?id=1', async () => { + const heroes = await firstValueFrom(http.get('api/heroes?id=1')); + expect(heroes.length).toBe(1, 'should find one hero w/id=1'); + }); - it('should return undefined for GET app/heroes?id=not-found-id', waitForAsync(() => { - http - .get('api/heroes?id=123456') - .subscribe((heroes) => expect(heroes.length).toBe(0), failRequest); - })); + it('should return undefined for GET app/heroes?id=not-found-id', async () => { + const heroes = await firstValueFrom(http.get('api/heroes?id=123456')); + expect(heroes.length).toBe(0); + }); - it('should return 404 for GET app/heroes/not-found-id', waitForAsync(() => { + it('should return 404 for GET app/heroes/not-found-id', async () => { const url = 'api/heroes/123456'; - http.get(url).subscribe( - () => fail(`should not have found data for '${url}'`), - (err) => expect(err.status).toBe(404, 'should have 404 status'), - ); - })); + try { + await firstValueFrom(http.get(url)); + fail(`should not have found data for '${url}'`); + } catch (err: any) { + expect(err.status).toBe(404, 'should have 404 status'); + } + }); - it('can generate the id when add a hero with no id', waitForAsync(() => { + it('can generate the id when add a hero with no id', async () => { const hero = new Hero(undefined, 'SuperDooper'); - http.post('api/heroes', hero).subscribe((replyHero) => { - expect(replyHero.id).toBeDefined('added hero should have an id'); - expect(replyHero).not.toBe(hero, 'reply hero should not be the request hero'); - }, failRequest); - })); + const replyHero = await firstValueFrom(http.post('api/heroes', hero)); + expect(replyHero.id).toBeDefined('added hero should have an id'); + expect(replyHero).not.toBe(hero, 'reply hero should not be the request hero'); + }); - it('can get nobodies (empty collection)', waitForAsync(() => { - http.get('api/nobodies').subscribe((nobodies) => { - expect(nobodies.length).toBe(0, 'should have no nobodies'); - }, failRequest); - })); + it('can get nobodies (empty collection)', async () => { + const nobodies = await firstValueFrom(http.get('api/nobodies')); + expect(nobodies.length).toBe(0, 'should have no nobodies'); + }); - it('can add a nobody with an id to empty nobodies collection', waitForAsync(() => { + it('can add a nobody with an id to empty nobodies collection', async () => { const id = 'g-u-i-d'; - http - .post('api/nobodies', {id, name: 'Noman'}) - .pipe(concatMap(() => http.get<{id: string; name: string}[]>('api/nobodies'))) - .subscribe((nobodies) => { - expect(nobodies.length).toBe(1, 'should a nobody'); - expect(nobodies[0].name).toBe('Noman', 'should be "Noman"'); - expect(nobodies[0].id).toBe(id, 'should preserve the submitted, ' + id); - }, failRequest); - })); - - it('should fail when add a nobody without an id to empty nobodies collection', waitForAsync(() => { - http.post('api/nobodies', {name: 'Noman'}).subscribe( - () => fail(`should not have been able to add 'Norman' to 'nobodies'`), - (err) => { - expect(err.status).toBe(422, 'should have 422 status'); - expect(err.body.error).toContain('id type is non-numeric'); - }, + const nobodies = await firstValueFrom( + http + .post('api/nobodies', {id, name: 'Noman'}) + .pipe(concatMap(() => http.get<{id: string; name: string}[]>('api/nobodies'))), ); - })); + expect(nobodies.length).toBe(1, 'should a nobody'); + expect(nobodies[0].name).toBe('Noman', 'should be "Noman"'); + expect(nobodies[0].id).toBe(id, 'should preserve the submitted, ' + id); + }); + + it('should fail when add a nobody without an id to empty nobodies collection', async () => { + try { + await firstValueFrom(http.post('api/nobodies', {name: 'Noman'})); + fail(`should not have been able to add 'Norman' to 'nobodies'`); + } catch (err: any) { + expect(err.status).toBe(422, 'should have 422 status'); + expect(err.body.error).toContain('id type is non-numeric'); + } + }); describe('can reset the database', () => { - it('to empty (object db)', waitForAsync(() => resetDatabaseTest('object'))); + it('to empty (object db)', () => resetDatabaseTest('object')); - it('to empty (observable db)', waitForAsync(() => resetDatabaseTest('observable'))); + it('to empty (observable db)', () => resetDatabaseTest('observable')); - it('to empty (promise db)', waitForAsync(() => resetDatabaseTest('promise'))); + it('to empty (promise db)', () => resetDatabaseTest('promise')); - function resetDatabaseTest(returnType: string) { + async function resetDatabaseTest(returnType: string) { // Observable of the number of heroes and nobodies const sizes$ = zip( http.get('api/heroes'), @@ -222,19 +215,17 @@ describe('HttpClient Backend Service', () => { ).pipe(map(([h, n, s]) => ({heroes: h.length, nobodies: n.length, stringers: s.length}))); // Add a nobody so that we have one - http - .post('api/nobodies', {id: 42, name: 'Noman'}) - .pipe( + const sizes = await firstValueFrom( + http.post('api/nobodies', {id: 42, name: 'Noman'}).pipe( // Reset database with "clear" option concatMap(() => http.post('commands/resetDb', {clear: true, returnType})), // get the number of heroes and nobodies concatMap(() => sizes$), - ) - .subscribe((sizes) => { - expect(sizes.heroes).toBe(0, 'reset should have cleared the heroes'); - expect(sizes.nobodies).toBe(0, 'reset should have cleared the nobodies'); - expect(sizes.stringers).toBe(0, 'reset should have cleared the stringers'); - }, failRequest); + ), + ); + expect(sizes.heroes).toBe(0, 'reset should have cleared the heroes'); + expect(sizes.nobodies).toBe(0, 'reset should have cleared the nobodies'); + expect(sizes.stringers).toBe(0, 'reset should have cleared the stringers'); } }); }); @@ -253,79 +244,71 @@ describe('HttpClient Backend Service', () => { http = TestBed.inject(HttpClient); }); - it('can get heroes', waitForAsync(() => { - http - .get('api/heroes') - .subscribe( - (heroes) => expect(heroes.length).toBeGreaterThan(0, 'should have heroes'), - failRequest, - ); - })); + it('can get heroes', async () => { + const heroes = await firstValueFrom(http.get('api/heroes')); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }); - it('can translate `foo/heroes` to `heroes` via `parsedRequestUrl` override', waitForAsync(() => { - http - .get('api/foo/heroes') - .subscribe( - (heroes) => expect(heroes.length).toBeGreaterThan(0, 'should have heroes'), - failRequest, - ); - })); + it('can translate `foo/heroes` to `heroes` via `parsedRequestUrl` override', async () => { + const heroes = await firstValueFrom(http.get('api/foo/heroes')); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }); - it('can get villains', waitForAsync(() => { - http - .get('api/villains') - .subscribe( - (villains) => expect(villains.length).toBeGreaterThan(0, 'should have villains'), - failRequest, - ); - })); + it('can get villains', async () => { + const villains = await firstValueFrom(http.get('api/villains')); + expect(villains.length).toBeGreaterThan(0, 'should have villains'); + }); - it('should 404 when POST to villains', waitForAsync(() => { + it('should 404 when POST to villains', async () => { const url = 'api/villains'; - http.post(url, {id: 42, name: 'Dr. Evil'}).subscribe( - () => fail(`should not have POSTed data for '${url}'`), - (err) => expect(err.status).toBe(404, 'should have 404 status'), - ); - })); + try { + await firstValueFrom(http.post(url, {id: 42, name: 'Dr. Evil'})); + fail(`should not have POSTed data for '${url}'`); + } catch (err: any) { + expect(err.status).toBe(404, 'should have 404 status'); + } + }); - it('should 404 when GET unknown collection', waitForAsync(() => { + it('should 404 when GET unknown collection', async () => { const url = 'api/unknown-collection'; - http.get(url).subscribe( - () => fail(`should not have found data for '${url}'`), - (err) => expect(err.status).toBe(404, 'should have 404 status'), + try { + await firstValueFrom(http.get(url)); + fail(`should not have found data for '${url}'`); + } catch (err: any) { + expect(err.status).toBe(404, 'should have 404 status'); + } + }); + + it('should use genId override to add new hero, "Maxinius"', async () => { + const heroes = await firstValueFrom( + http + .post('api/heroes', {name: 'Maxinius'}) + .pipe(concatMap(() => http.get('api/heroes?name=Maxi'))), ); - })); + expect(heroes.length).toBe(1, 'should have found "Maxinius"'); + expect(heroes[0].name).toBe('Maxinius'); + expect(heroes[0].id).toBeGreaterThan(1000); + }); - it('should use genId override to add new hero, "Maxinius"', waitForAsync(() => { - http - .post('api/heroes', {name: 'Maxinius'}) - .pipe(concatMap(() => http.get('api/heroes?name=Maxi'))) - .subscribe((heroes) => { - expect(heroes.length).toBe(1, 'should have found "Maxinius"'); - expect(heroes[0].name).toBe('Maxinius'); - expect(heroes[0].id).toBeGreaterThan(1000); - }, failRequest); - })); - - it('should use genId override guid generator for a new nobody without an id', waitForAsync(() => { - http - .post('api/nobodies', {name: 'Noman'}) - .pipe(concatMap(() => http.get<{id: string; name: string}[]>('api/nobodies'))) - .subscribe((nobodies) => { - expect(nobodies.length).toBe(1, 'should a nobody'); - expect(nobodies[0].name).toBe('Noman', 'should be "Noman"'); - expect(typeof nobodies[0].id).toBe('string', 'should create a string (guid) id'); - }, failRequest); - })); + it('should use genId override guid generator for a new nobody without an id', async () => { + const nobodies = await firstValueFrom( + http + .post('api/nobodies', {name: 'Noman'}) + .pipe(concatMap(() => http.get<{id: string; name: string}[]>('api/nobodies'))), + ); + expect(nobodies.length).toBe(1, 'should a nobody'); + expect(nobodies[0].name).toBe('Noman', 'should be "Noman"'); + expect(typeof nobodies[0].id).toBe('string', 'should create a string (guid) id'); + }); describe('can reset the database', () => { - it('to empty (object db)', waitForAsync(() => resetDatabaseTest('object'))); + it('to empty (object db)', () => resetDatabaseTest('object')); - it('to empty (observable db)', waitForAsync(() => resetDatabaseTest('observable'))); + it('to empty (observable db)', () => resetDatabaseTest('observable')); - it('to empty (promise db)', waitForAsync(() => resetDatabaseTest('promise'))); + it('to empty (promise db)', () => resetDatabaseTest('promise')); - function resetDatabaseTest(returnType: string) { + async function resetDatabaseTest(returnType: string) { // Observable of the number of heroes, nobodies and villains const sizes$ = zip( http.get('api/heroes'), @@ -342,20 +325,18 @@ describe('HttpClient Backend Service', () => { ); // Add a nobody so that we have one - http - .post('api/nobodies', {id: 42, name: 'Noman'}) - .pipe( + const sizes = await firstValueFrom( + http.post('api/nobodies', {id: 42, name: 'Noman'}).pipe( // Reset database with "clear" option concatMap(() => http.post('commands/resetDb', {clear: true, returnType})), // count all the collections concatMap(() => sizes$), - ) - .subscribe((sizes) => { - expect(sizes.heroes).toBe(0, 'reset should have cleared the heroes'); - expect(sizes.nobodies).toBe(0, 'reset should have cleared the nobodies'); - expect(sizes.stringers).toBe(0, 'reset should have cleared the stringers'); - expect(sizes.villains).toBeGreaterThan(0, 'reset should NOT clear villains'); - }, failRequest); + ), + ); + expect(sizes.heroes).toBe(0, 'reset should have cleared the heroes'); + expect(sizes.nobodies).toBe(0, 'reset should have cleared the nobodies'); + expect(sizes.stringers).toBe(0, 'reset should have cleared the stringers'); + expect(sizes.villains).toBeGreaterThan(0, 'reset should NOT clear villains'); } }); }); @@ -378,86 +359,73 @@ describe('HttpClient Backend Service', () => { heroService = TestBed.inject(HeroService); }); - it('can get heroes', waitForAsync(() => { - heroService.getHeroes().subscribe((heroes) => { - expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); - }, failRequest); - })); + it('can get heroes', async () => { + const heroes = await firstValueFrom(heroService.getHeroes()); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }); - it('can get hero w/ id=1', waitForAsync(() => { - heroService.getHero(1).subscribe( - (hero) => { - expect(hero.name).toBe('Windstorm'); - }, - () => fail('getHero failed'), - ); - })); + it('can get hero w/ id=1', async () => { + const hero = await firstValueFrom(heroService.getHero(1)); + expect(hero.name).toBe('Windstorm'); + }); - it('should 404 when hero id not found', waitForAsync(() => { + it('should 404 when hero id not found', async () => { const id = 123456; - heroService.getHero(id).subscribe( - () => fail(`should not have found hero for id='${id}'`), - (err) => { - expect(err.status).toBe(404, 'should have 404 status'); - }, - ); - })); + try { + await firstValueFrom(heroService.getHero(id)); + fail(`should not have found hero for id='${id}'`); + } catch (err: any) { + expect(err.status).toBe(404, 'should have 404 status'); + } + }); - it('can add a hero', waitForAsync(() => { - heroService - .addHero('FunkyBob') - .pipe( + it('can add a hero', async () => { + const hero = await firstValueFrom( + heroService.addHero('FunkyBob').pipe( tap((hero) => expect(hero.name).toBe('FunkyBob')), // Get the new hero by its generated id concatMap((hero) => heroService.getHero(hero.id)), - ) - .subscribe( - (hero) => { - expect(hero.name).toBe('FunkyBob'); - }, - () => failRequest('re-fetch of new hero failed'), - ); - }), 10000); + ), + ); + expect(hero.name).toBe('FunkyBob'); + }, 10000); - it('can delete a hero', waitForAsync(() => { + it('can delete a hero', async () => { const id = 1; - heroService.deleteHero(id).subscribe((_: {}) => expect(_).toBeDefined(), failRequest); - })); + const res = await firstValueFrom(heroService.deleteHero(id)); + expect(res).toBeDefined(); + }); - it('should allow delete of non-existent hero', waitForAsync(() => { + it('should allow delete of non-existent hero', async () => { const id = 123456; - heroService.deleteHero(id).subscribe((_: {}) => expect(_).toBeDefined(), failRequest); - })); + const res = await firstValueFrom(heroService.deleteHero(id)); + expect(res).toBeDefined(); + }); - it('can search for heroes by name containing "a"', waitForAsync(() => { - heroService.searchHeroes('a').subscribe((heroes: Hero[]) => { - expect(heroes.length).toBe(3, 'should find 3 heroes with letter "a"'); - }, failRequest); - })); + it('can search for heroes by name containing "a"', async () => { + const heroes = await firstValueFrom(heroService.searchHeroes('a')); + expect(heroes.length).toBe(3, 'should find 3 heroes with letter "a"'); + }); - it('can update existing hero', waitForAsync(() => { + it('can update existing hero', async () => { const id = 1; - heroService - .getHero(id) - .pipe( + const hero = await firstValueFrom( + heroService.getHero(id).pipe( concatMap((hero) => { hero.name = 'Thunderstorm'; return heroService.updateHero(hero); }), concatMap(() => heroService.getHero(id)), - ) - .subscribe( - (hero) => expect(hero.name).toBe('Thunderstorm'), - () => fail('re-fetch of updated hero failed'), - ); - }), 10000); + ), + ); + expect(hero.name).toBe('Thunderstorm'); + }, 10000); - it('should create new hero when try to update non-existent hero', waitForAsync(() => { + it('should create new hero when try to update non-existent hero', async () => { const falseHero = new Hero(12321, 'DryMan'); - heroService - .updateHero(falseHero) - .subscribe((hero) => expect(hero.name).toBe(falseHero.name), failRequest); - })); + const hero = await firstValueFrom(heroService.updateHero(falseHero)); + expect(hero.name).toBe(falseHero.name); + }); }); }); @@ -508,38 +476,45 @@ describe('HttpClient Backend Service', () => { expect(ti).toBeDefined(); }); - it('should have GET request header from test interceptor', waitForAsync(() => { + it('should have GET request header from test interceptor', async () => { const handle = spyOn(httpBackend, 'handle').and.callThrough(); - http.get('api/heroes').subscribe((heroes) => { - // HttpRequest is first arg of the first call to in-mem backend `handle` - const req: HttpRequest = handle.calls.argsFor(0)[0]; - const reqHeader = req.headers.get('x-test-req'); - expect(reqHeader).toBe('req-test-header'); + const heroes = await firstValueFrom(http.get('api/heroes')); + // HttpRequest is first arg of the first call to in-mem backend `handle` + const req: HttpRequest = handle.calls.argsFor(0)[0]; + const reqHeader = req.headers.get('x-test-req'); + expect(reqHeader).toBe('req-test-header'); - expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); - }, failRequest); - })); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }); - it('should have GET response header from test interceptor', waitForAsync(() => { + it('should have GET response header from test interceptor', async () => { let gotResponse = false; const req = new HttpRequest('GET', 'api/heroes'); - http.request(req).subscribe( - (event) => { - if (event.type === HttpEventType.Response) { - gotResponse = true; + await new Promise((resolve, reject) => { + http.request(req).subscribe( + (event) => { + if (event.type === HttpEventType.Response) { + gotResponse = true; - const resHeader = event.headers.get('x-test-res'); - expect(resHeader).toBe('res-test-header'); + const resHeader = event.headers.get('x-test-res'); + expect(resHeader).toBe('res-test-header'); - const heroes = event.body as Hero[]; - expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); - } - }, - failRequest, - () => expect(gotResponse).toBe(true, 'should have seen Response event'), - ); - })); + const heroes = event.body as Hero[]; + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + } + }, + (err) => { + failRequest(err); + reject(err); + }, + () => { + expect(gotResponse).toBe(true, 'should have seen Response event'); + resolve(); + }, + ); + }); + }); }); describe('HttpClient passThru', () => { @@ -568,28 +543,46 @@ describe('HttpClient Backend Service', () => { spyOn(httpBackend, 'handle').and.returnValue(mockPassThroughResponse); }); - it('can get heroes (no passthru)', waitForAsync(() => { - http.get('api/heroes').subscribe((heroes) => { - expect(createPassThruBackend).not.toHaveBeenCalled(); - expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); - }, failRequest); - })); + it('can get heroes (no passthru)', async () => { + await new Promise((resolve) => { + http.get('api/heroes').subscribe({ + next: (heroes) => { + expect(createPassThruBackend).not.toHaveBeenCalled(); + expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); + }, + error: failRequest, + complete: resolve, + }); + }); + }); // `passthru` is NOT a collection in the data store // so requests for it should pass thru to the "real" server - it('can GET passthru', waitForAsync(() => { - http.get('api/passthru').subscribe((passthru) => { - expect(passthru.length).toBeGreaterThan(0, 'should have passthru data'); - }, failRequest); - })); + it('can GET passthru', async () => { + await new Promise((resolve) => { + http.get('api/passthru').subscribe({ + next: (passthru) => { + expect(passthru.length).toBeGreaterThan(0, 'should have passthru data'); + }, + error: failRequest, + complete: resolve, + }); + }); + }); - it('can ADD to passthru', waitForAsync(() => { - http.post('api/passthru', {name: 'Dude'}).subscribe((passthru) => { - expect(passthru).toBeDefined('should have passthru data'); - expect(passthru.id).toBe(42, 'passthru object should have id 42'); - }, failRequest); - })); + it('can ADD to passthru', async () => { + await new Promise((resolve) => { + http.post('api/passthru', {name: 'Dude'}).subscribe({ + next: (passthru) => { + expect(passthru).toBeDefined('should have passthru data'); + expect(passthru.id).toBe(42, 'passthru object should have id 42'); + }, + error: failRequest, + complete: resolve, + }); + }); + }); }); describe('HttpClient passThru creation', () => { @@ -624,15 +617,12 @@ describe('HttpClient Backend Service', () => { http = TestBed.inject(HttpClient); }); - it('can get heroes (encapsulated)', waitForAsync(() => { - http - .get<{data: any}>('api/heroes') - .pipe(map((data) => data.data as Hero[])) - .subscribe( - (heroes) => expect(heroes.length).toBeGreaterThan(0, 'should have data.heroes'), - failRequest, - ); - })); + it('can get heroes (encapsulated)', async () => { + const heroes = await firstValueFrom( + http.get<{data: any}>('api/heroes').pipe(map((data) => data.data as Hero[])), + ); + expect(heroes.length).toBeGreaterThan(0, 'should have data.heroes'); + }); }); describe('when using the FetchBackend', () => { diff --git a/packages/platform-browser-dynamic/test/testing_public_browser_spec.ts b/packages/platform-browser-dynamic/test/testing_public_browser_spec.ts index e805c4b06c4..ea06258f486 100644 --- a/packages/platform-browser-dynamic/test/testing_public_browser_spec.ts +++ b/packages/platform-browser-dynamic/test/testing_public_browser_spec.ts @@ -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(); diff --git a/packages/platform-browser/test/testing_public_spec.ts b/packages/platform-browser/test/testing_public_spec.ts index 7bbc5cf9fcb..e6b4b5b6fc0 100644 --- a/packages/platform-browser/test/testing_public_spec.ts +++ b/packages/platform-browser/test/testing_public_spec.ts @@ -141,6 +141,16 @@ class SomeLibModule {} const aTok = new InjectionToken('a'); const bTok = new InjectionToken('b'); +const {withProxyZone: _withProxyZone} = (Zone as any)[Zone.__symbol__('fakeAsyncTest')]; +const withProxyZone = (fn: T): T => { + const proxied = _withProxyZone(fn); + return (fn.length + ? function (this: unknown, done: DoneFn) { + return proxied.call(this, done); + } + : proxied) as unknown as T; +}; + describe('public testing API', () => { describe('using the async helper with context passing', () => { type TestContext = {actuallyDone: boolean}; @@ -164,14 +174,24 @@ describe('public testing API', () => { }, 0); }); - it('should run async tests with tasks', waitForAsync(function (this: TestContext) { - setTimeout(() => (this.actuallyDone = true), 0); - })); + it( + 'should run async tests with tasks', + withProxyZone( + waitForAsync(function (this: TestContext) { + setTimeout(() => (this.actuallyDone = true), 0); + }), + ), + ); - it('should run async tests with promises', waitForAsync(function (this: TestContext) { - const p = new Promise((resolve, reject) => setTimeout(resolve, 10)); - p.then(() => (this.actuallyDone = true)); - })); + it( + 'should run async tests with promises', + withProxyZone( + waitForAsync(function (this: TestContext) { + const p = new Promise((resolve, reject) => setTimeout(resolve, 10)); + p.then(() => (this.actuallyDone = true)); + }), + ), + ); }); describe('basic context passing to inject, fakeAsync and withModule helpers', () => { @@ -193,9 +213,14 @@ describe('public testing API', () => { this.contextModified = true; })); - it('should pass context to fakeAsync helper', fakeAsync(function (this: TestContext) { - this.contextModified = true; - })); + it( + 'should pass context to fakeAsync helper', + withProxyZone( + fakeAsync(function (this: TestContext) { + this.contextModified = true; + }), + ), + ); it( 'should pass context to withModule helper - simple', @@ -215,18 +240,28 @@ describe('public testing API', () => { ), ); - it('should preserve context when async and inject helpers are combined', waitForAsync( - inject([], function (this: TestContext) { - setTimeout(() => (this.contextModified = true), 0); - }), - )); + it( + 'should preserve context when async and inject helpers are combined', + withProxyZone( + waitForAsync( + inject([], function (this: TestContext) { + setTimeout(() => (this.contextModified = true), 0); + }), + ), + ), + ); - it('should preserve context when fakeAsync and inject helpers are combined', fakeAsync( - inject([], function (this: TestContext) { - setTimeout(() => (this.contextModified = true), 0); - tick(1); - }), - )); + it( + 'should preserve context when fakeAsync and inject helpers are combined', + withProxyZone( + fakeAsync( + inject([], function (this: TestContext) { + setTimeout(() => (this.contextModified = true), 0); + tick(1); + }), + ), + ), + ); }); describe('using the test injector with the inject helper', () => { @@ -241,21 +276,31 @@ describe('public testing API', () => { expect(service.value).toEqual('real value'); })); - it('should wait until returned promises', waitForAsync( - inject([FancyService], (service: FancyService) => { - service.getAsyncValue().then((value) => expect(value).toEqual('async value')); - service.getTimeoutValue().then((value) => expect(value).toEqual('timeout value')); - }), - )); + it( + 'should wait until returned promises', + withProxyZone( + waitForAsync( + inject([FancyService], (service: FancyService) => { + service.getAsyncValue().then((value) => expect(value).toEqual('async value')); + service.getTimeoutValue().then((value) => expect(value).toEqual('timeout value')); + }), + ), + ), + ); - it('should allow the use of fakeAsync', fakeAsync( - inject([FancyService], (service: FancyService) => { - let value: string = undefined!; - service.getAsyncValue().then((val) => (value = val)); - tick(); - expect(value).toEqual('async value'); - }), - )); + it( + 'should allow the use of fakeAsync', + withProxyZone( + fakeAsync( + inject([FancyService], (service: FancyService) => { + let value: string = undefined!; + service.getAsyncValue().then((val) => (value = val)); + tick(); + expect(value).toEqual('async value'); + }), + ), + ), + ); it('should allow use of "done"', (done) => { inject([FancyService], (service: FancyService) => { @@ -281,11 +326,15 @@ describe('public testing API', () => { }); describe('using async beforeEach', () => { - beforeEach(waitForAsync( - inject([FancyService], (service: FancyService) => { - service.getAsyncValue().then((value) => (service.value = value)); - }), - )); + beforeEach( + withProxyZone( + waitForAsync( + inject([FancyService], (service: FancyService) => { + service.getAsyncValue().then((value) => (service.value = value)); + }), + ), + ), + ); it('should use asynchronously modified value', inject( [FancyService], @@ -877,7 +926,7 @@ describe('public testing API', () => { describe('setting up the compiler', () => { describe('providers', () => { // TODO(alxhub): disable while we figure out how this should work - xit('should use set up providers', fakeAsync(() => { + xit('should use set up providers', async () => { // Keeping this component inside the test is needed to make sure it's not resolved // prior to this test, thus having ɵcmp and a reference in resource // resolution queue. This is done to check external resoution logic in isolation by @@ -895,43 +944,37 @@ describe('public testing API', () => { providers: [{provide: ResourceLoader, useValue: {get: resourceLoaderGet}}], }); - tick(); const compFixture = TestBed.createComponent(InternalCompWithUrlTemplate); + await compFixture.whenStable(); expect(compFixture.nativeElement).toHaveText('Hello world!'); - })); + }); }); }); }); describe('errors', () => { - let originalJasmineIt: (description: string, func: () => void) => jasmine.Spec; - - const patchJasmineIt = () => { + const runAsyncTestFn = (fn: (done: DoneFn) => void) => { const {promise, resolve, reject} = Promise.withResolvers(); - const jasmineEnv = jasmine.getEnv() as any; - originalJasmineIt = jasmineEnv.it; - jasmineEnv.it = (description: string, fn: (done: DoneFn) => void): any => { - const done = (() => resolve(null)); - done.fail = (err) => reject(err); - fn(done); - return null; - }; + const done = (() => resolve(null)); + done.fail = (err) => reject(err); + fn(done); return promise; }; - const restoreJasmineIt = () => ((jasmine.getEnv() as any).it = originalJasmineIt); - it('should fail when an asynchronous error is thrown', (done) => { - const itPromise = patchJasmineIt(); const barError = new Error('bar'); - it('throws an async error', waitForAsync( - inject([], () => - setTimeout(() => { - throw barError; - }, 0), + const itPromise = runAsyncTestFn( + withProxyZone( + waitForAsync( + inject([], () => + setTimeout(() => { + throw barError; + }, 0), + ), + ), ), - )); + ); itPromise.then( () => done.fail('Expected test to fail, but it did not'), @@ -940,21 +983,22 @@ describe('public testing API', () => { done(); }, ); - restoreJasmineIt(); }); it('should fail when a returned promise is rejected', (done) => { - const itPromise = patchJasmineIt(); + const itPromise = runAsyncTestFn( + withProxyZone( + waitForAsync( + inject([], () => { + const {promise, reject} = Promise.withResolvers(); + const p = promise.then(() => expect(1).toEqual(2)); - it('should fail with an error from a promise', waitForAsync( - inject([], () => { - const {promise, reject} = Promise.withResolvers(); - const p = promise.then(() => expect(1).toEqual(2)); - - reject('baz'); - return p; - }), - )); + reject('baz'); + return p; + }), + ), + ), + ); itPromise.then( () => done.fail('Expected test to fail, but it did not'), @@ -963,7 +1007,6 @@ describe('public testing API', () => { done(); }, ); - restoreJasmineIt(); }); describe('components', () => { @@ -1008,14 +1051,14 @@ Did you run and wait for 'resolveComponentResources()'?`); describe('creating components', () => { beforeEach(() => {}); - it('should instantiate a component with valid DOM', waitForAsync(async () => { + it('should instantiate a component with valid DOM', async () => { const fixture = TestBed.createComponent(ChildComp); await fixture.whenStable(); expect(fixture.nativeElement).toHaveText('Original Child'); - })); + }); - it('should allow changing members of the component', waitForAsync(async () => { + it('should allow changing members of the component', async () => { const componentFixture = TestBed.createComponent(MyIfComp); await componentFixture.whenStable(); expect(componentFixture.nativeElement).toHaveText('MyIf()'); @@ -1023,25 +1066,25 @@ Did you run and wait for 'resolveComponentResources()'?`); componentFixture.componentInstance.showMore.set(true); await componentFixture.whenStable(); expect(componentFixture.nativeElement).toHaveText('MyIf(More)'); - })); + }); - it('should override a template', waitForAsync(async () => { + it('should override a template', async () => { TestBed.overrideComponent(ChildComp, {set: {template: 'Mock'}}); const componentFixture = TestBed.createComponent(ChildComp); await componentFixture.whenStable(); expect(componentFixture.nativeElement).toHaveText('Mock'); - })); + }); - it('should override a provider', waitForAsync(async () => { + it('should override a provider', async () => { TestBed.overrideComponent(TestProvidersComp, { set: {providers: [{provide: FancyService, useClass: MockFancyService}]}, }); const componentFixture = TestBed.createComponent(TestProvidersComp); await componentFixture.whenStable(); expect(componentFixture.nativeElement).toHaveText('injected value: mocked out value'); - })); + }); - it('should override a viewProvider', waitForAsync(async () => { + it('should override a viewProvider', async () => { TestBed.overrideComponent(TestViewProvidersComp, { set: {viewProviders: [{provide: FancyService, useClass: MockFancyService}]}, }); @@ -1049,7 +1092,7 @@ Did you run and wait for 'resolveComponentResources()'?`); const componentFixture = TestBed.createComponent(TestViewProvidersComp); await componentFixture.whenStable(); expect(componentFixture.nativeElement).toHaveText('injected value: mocked out value'); - })); + }); describe('getLastFixture', () => { it('should return the last created fixture', () => { @@ -1077,12 +1120,12 @@ Did you run and wait for 'resolveComponentResources()'?`); describe('using alternate components', () => { beforeEach(() => {}); - it('should override component dependencies', waitForAsync(() => { + it('should override component dependencies', async () => { TestBed.overrideComponent(ParentComp, {set: {imports: [MockChildComp]}}); const componentFixture = TestBed.createComponent(ParentComp); - componentFixture.detectChanges(); + await componentFixture.whenStable(); expect(componentFixture.nativeElement).toHaveText('Parent(Mock)'); - })); + }); }); describe('calling override methods after TestBed initialization', () => { diff --git a/packages/router/upgrade/test/upgrade.spec.ts b/packages/router/upgrade/test/upgrade.spec.ts index ed018634fc5..cf62843e158 100644 --- a/packages/router/upgrade/test/upgrade.spec.ts +++ b/packages/router/upgrade/test/upgrade.spec.ts @@ -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; + }); }); diff --git a/packages/service-worker/test/BUILD.bazel b/packages/service-worker/test/BUILD.bazel index ea5f4a78c56..cb90f374026 100644 --- a/packages/service-worker/test/BUILD.bazel +++ b/packages/service-worker/test/BUILD.bazel @@ -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", diff --git a/packages/service-worker/test/provider_spec.ts b/packages/service-worker/test/provider_spec.ts index fdb85c738dd..dba974ab9d5 100644 --- a/packages/service-worker/test/provider_spec.ts +++ b/packages/service-worker/test/provider_spec.ts @@ -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(); + const whenStable = () => + new Promise((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:`', fakeAsync(() => { + it('registers the SW when the app stabilizes with `registerWhenStable:`', 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:`', fakeAsync(() => { + it('registers the SW after `timeout` if the app does not stabilize with `registerWhenStable:`', 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:`', fakeAsync(() => { + it('registers the SW after the specified delay with `registerWithDelay:`', 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(); 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( diff --git a/packages/upgrade/static/test/integration/change_detection_spec.ts b/packages/upgrade/static/test/integration/change_detection_spec.ts index d969c02fb3c..c0d12d74087 100644 --- a/packages/upgrade/static/test/integration/change_detection_spec.ts +++ b/packages/upgrade/static/test/integration/change_detection_spec.ts @@ -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(''); @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("
{{reset(); l('1A');}}{{l('1B')}}{{l('1C')}}
"); - 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(''); - 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 diff --git a/packages/upgrade/static/test/integration/content_projection_spec.ts b/packages/upgrade/static/test/integration/content_projection_spec.ts index ba1afa2da2e..47aaa693bb2 100644 --- a/packages/upgrade/static/test/integration/content_projection_spec.ts +++ b/packages/upgrade/static/test/integration/content_projection_spec.ts @@ -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("
{{ 'ng1[' }}~{{ ngContent }}~{{ ']' }}
"); - 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 }}()', @@ -107,12 +105,11 @@ withEachNg1Version(() => { `); - 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(' }}{{ transclude }} { const element = html("
{{ 'ng1(' }}{{ ')' }}
"); - 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(() => { '
1a
1b
', ); - 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)'); + }); }); }); diff --git a/packages/upgrade/static/test/integration/downgrade_component_spec.ts b/packages/upgrade/static/test/integration/downgrade_component_spec.ts index 24b1ab21bb8..88571c2edb9 100644 --- a/packages/upgrade/static/test/integration/downgrade_component_spec.ts +++ b/packages/upgrade/static/test/integration/downgrade_component_spec.ts @@ -26,9 +26,9 @@ import { Output, SimpleChanges, } from '@angular/core'; -import {fakeAsync, tick, 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'; @@ -46,7 +46,7 @@ withEachNg1Version(() => { beforeEach(() => destroyPlatform()); afterEach(() => destroyPlatform()); - it('should bind properties, events', waitForAsync(() => { + it('should bind properties, events', async () => { const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => { $rootScope['name'] = 'world'; $rootScope['dataA'] = 'A'; @@ -158,25 +158,24 @@ withEachNg1Version(() => { | modelA: {{modelA}}; modelB: {{modelB}}; eventA: {{eventA}}; eventB: {{eventB}}; `); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(document.body.textContent)).toEqual( - 'ignore: -; ' + - 'literal: Text; interpolate: Hello world; ' + - 'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (2) | ' + - 'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;', - ); + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toEqual( + 'ignore: -; ' + + 'literal: Text; interpolate: Hello world; ' + + 'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (2) | ' + + 'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;', + ); - $apply(upgrade, 'name = "everyone"'); - expect(multiTrim(document.body.textContent)).toEqual( - 'ignore: -; ' + - 'literal: Text; interpolate: Hello everyone; ' + - 'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (3) | ' + - 'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;', - ); - }); - })); + $apply(upgrade, 'name = "everyone"'); + expect(multiTrim(document.body.textContent)).toEqual( + 'ignore: -; ' + + 'literal: Text; interpolate: Hello everyone; ' + + 'oneWayA: A; oneWayB: B; twoWayA: newA; twoWayB: newB; (3) | ' + + 'modelA: newA; modelB: newB; eventA: aFired; eventB: bFired;', + ); + }); - it('should bind properties to signal inputs', waitForAsync(() => { + it('should bind properties to signal inputs', async () => { const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => { $rootScope['name'] = 'world'; }); @@ -213,15 +212,14 @@ withEachNg1Version(() => { `); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(document.body.textContent)).toEqual('Message: Hello world'); + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toEqual('Message: Hello world'); - $apply(upgrade, 'name = "everyone"'); - expect(multiTrim(document.body.textContent)).toEqual('Message: Hello everyone'); - }); - })); + $apply(upgrade, 'name = "everyone"'); + expect(multiTrim(document.body.textContent)).toEqual('Message: Hello everyone'); + }); - it('should propagate AngularJS→Angular changes through model() signals', waitForAsync(() => { + it('should propagate AngularJS→Angular changes through model() signals', async () => { const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => { $rootScope['value'] = 'initial'; }); @@ -253,20 +251,19 @@ withEachNg1Version(() => { | value: {{value}} `); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(document.body.textContent)).toEqual('Value: initial | value: initial'); + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toEqual('Value: initial | value: initial'); - $apply(upgrade, 'value = "updated"'); - expect(multiTrim(document.body.textContent)).toEqual('Value: updated | value: updated'); - }); - })); + $apply(upgrade, 'value = "updated"'); + expect(multiTrim(document.body.textContent)).toEqual('Value: updated | value: updated'); + }); - it('should propagate Angular→AngularJS changes through model() signals', waitForAsync(() => { + it('should propagate Angular→AngularJS changes through model() signals', async () => { const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => { $rootScope['value'] = 'initial'; }); - let componentInstance: Ng2Component; + let componentInstance!: Ng2Component; @Component({ selector: 'ng2', @@ -298,17 +295,16 @@ withEachNg1Version(() => { | value: {{value}} `); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(document.body.textContent)).toEqual('Value: initial | value: initial'); + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toEqual('Value: initial | value: initial'); - $apply(upgrade, () => componentInstance.value.set('from-angular')); - expect(multiTrim(document.body.textContent)).toEqual( - 'Value: from-angular | value: from-angular', - ); - }); - })); + $apply(upgrade, () => componentInstance.value.set('from-angular')); + expect(multiTrim(document.body.textContent)).toEqual( + 'Value: from-angular | value: from-angular', + ); + }); - it('should bind properties to onpush components', waitForAsync(() => { + it('should bind properties to onpush components', async () => { const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => { $rootScope['dataB'] = 'B'; }); @@ -342,14 +338,13 @@ withEachNg1Version(() => { `); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(document.body.textContent)).toEqual('oneWayB: B'); - $apply(upgrade, 'dataB= "everyone"'); - expect(multiTrim(document.body.textContent)).toEqual('oneWayB: everyone'); - }); - })); + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toEqual('oneWayB: B'); + $apply(upgrade, 'dataB= "everyone"'); + expect(multiTrim(document.body.textContent)).toEqual('oneWayB: everyone'); + }); - it('should support two-way binding and event listener', waitForAsync(() => { + it('should support two-way binding and event listener', async () => { const listenerSpy = jasmine.createSpy('$rootScope.listener'); const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => { $rootScope['value'] = 'world'; @@ -396,14 +391,13 @@ withEachNg1Version(() => { `); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(element.textContent)).toEqual('model: newC; | value: newC'); - expect(listenerSpy).toHaveBeenCalledWith('newC'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toEqual('model: newC; | value: newC'); + expect(listenerSpy).toHaveBeenCalledWith('newC'); + }); - it('should run change-detection on every digest (by default)', waitForAsync(() => { - let ng2Component: Ng2Component; + it('should run change-detection on every digest (by default)', async () => { + let ng2Component!: Ng2Component; @Component({ selector: 'ng2', @@ -431,49 +425,51 @@ withEachNg1Version(() => { const ng1Module = angular .module_('ng1', []) .directive('ng2', downgradeComponent({component: Ng2Component})) - .run(($rootScope: angular.IRootScopeService) => { - $rootScope['value1'] = 0; - $rootScope['value2'] = 0; - }); + .run([ + $ROOT_SCOPE, + ($rootScope: angular.IRootScopeService) => { + $rootScope['value1'] = 0; + $rootScope['value2'] = 0; + }, + ]); const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService; + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService; - expect(element.textContent).toBe('0 | 0'); + expect(element.textContent).toBe('0 | 0'); - // Digest should invoke CD - $rootScope.$digest(); - $rootScope.$digest(); - expect(element.textContent).toBe('0 | 0'); + // Digest should invoke CD + $rootScope.$digest(); + $rootScope.$digest(); + expect(element.textContent).toBe('0 | 0'); - // Internal changes should be detected on digest - ng2Component.value1 = 1; - ng2Component.value2 = 2; - $rootScope.$digest(); - expect(element.textContent).toBe('1 | 2'); + // Internal changes should be detected on digest + ng2Component.value1 = 1; + ng2Component.value2 = 2; + $rootScope.$digest(); + expect(element.textContent).toBe('1 | 2'); - // Digest should propagate change in prop-bound input - $rootScope.$apply('value1 = 3'); - expect(element.textContent).toBe('3 | 2'); + // Digest should propagate change in prop-bound input + $rootScope.$apply('value1 = 3'); + expect(element.textContent).toBe('3 | 2'); - // Digest should propagate change in attr-bound input - ng2Component.value1 = 4; - $rootScope.$apply('value2 = 5'); - expect(element.textContent).toBe('4 | 5'); + // Digest should propagate change in attr-bound input + ng2Component.value1 = 4; + $rootScope.$apply('value2 = 5'); + expect(element.textContent).toBe('4 | 5'); - // Digest should propagate changes that happened before the digest - $rootScope['value1'] = 6; - expect(element.textContent).toBe('4 | 5'); + // Digest should propagate changes that happened before the digest + $rootScope['value1'] = 6; + expect(element.textContent).toBe('4 | 5'); - $rootScope.$digest(); - expect(element.textContent).toBe('6 | 5'); - }); - })); + $rootScope.$digest(); + expect(element.textContent).toBe('6 | 5'); + }); - it('should not run change-detection on every digest when opted out', waitForAsync(() => { - let ng2Component: Ng2Component; + it('should not run change-detection on every digest when opted out', async () => { + let ng2Component!: Ng2Component; @Component({ selector: 'ng2', @@ -501,46 +497,48 @@ withEachNg1Version(() => { const ng1Module = angular .module_('ng1', []) .directive('ng2', downgradeComponent({component: Ng2Component, propagateDigest: false})) - .run(($rootScope: angular.IRootScopeService) => { - $rootScope['value1'] = 0; - $rootScope['value2'] = 0; - }); + .run([ + $ROOT_SCOPE, + ($rootScope: angular.IRootScopeService) => { + $rootScope['value1'] = 0; + $rootScope['value2'] = 0; + }, + ]); const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService; + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const $rootScope = upgrade.$injector.get('$rootScope') as angular.IRootScopeService; - expect(element.textContent).toBe('0 | 0'); + expect(element.textContent).toBe('0 | 0'); - // Digest should not invoke CD - $rootScope.$digest(); - $rootScope.$digest(); - expect(element.textContent).toBe('0 | 0'); + // Digest should not invoke CD + $rootScope.$digest(); + $rootScope.$digest(); + expect(element.textContent).toBe('0 | 0'); - // Digest should not invoke CD, even if component values have changed (internally) - ng2Component.value1 = 1; - ng2Component.value2 = 2; - $rootScope.$digest(); - expect(element.textContent).toBe('0 | 0'); + // Digest should not invoke CD, even if component values have changed (internally) + ng2Component.value1 = 1; + ng2Component.value2 = 2; + $rootScope.$digest(); + expect(element.textContent).toBe('0 | 0'); - // Digest should invoke CD, if prop-bound input has changed - $rootScope.$apply('value1 = 3'); - expect(element.textContent).toBe('3 | 2'); + // Digest should invoke CD, if prop-bound input has changed + $rootScope.$apply('value1 = 3'); + expect(element.textContent).toBe('3 | 2'); - // Digest should invoke CD, if attr-bound input has changed - ng2Component.value1 = 4; - $rootScope.$apply('value2 = 5'); - expect(element.textContent).toBe('4 | 5'); + // Digest should invoke CD, if attr-bound input has changed + ng2Component.value1 = 4; + $rootScope.$apply('value2 = 5'); + expect(element.textContent).toBe('4 | 5'); - // Digest should invoke CD, if input has changed before the digest - $rootScope['value1'] = 6; - $rootScope.$digest(); - expect(element.textContent).toBe('6 | 5'); - }); - })); + // Digest should invoke CD, if input has changed before the digest + $rootScope['value1'] = 6; + $rootScope.$digest(); + expect(element.textContent).toBe('6 | 5'); + }); - it('should still run normal Angular change-detection regardless of `propagateDigest`', fakeAsync(() => { + it('should still run normal Angular change-detection regardless of `propagateDigest`', async () => { @Component({ selector: 'ng2', template: '{{ value }}', @@ -550,7 +548,7 @@ withEachNg1Version(() => { class Ng2Component { value = 'foo'; constructor() { - setTimeout(() => (this.value = 'bar'), 1000); + setTimeout(() => (this.value = 'bar')); } } @@ -569,15 +567,14 @@ withEachNg1Version(() => { const element = html(' | '); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(element.textContent).toBe('foo | foo'); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(element.textContent).toBe('foo | foo'); - tick(1000); - expect(element.textContent).toBe('bar | bar'); - }); - })); + await timeout(); + expect(element.textContent).toBe('bar | bar'); + }); - it('should initialize inputs in time for `ngOnChanges`', waitForAsync(() => { + it('should initialize inputs in time for `ngOnChanges`', async () => { @Component({ selector: 'ng2', template: ` ngOnChangesCount: {{ ngOnChangesCount }} | firstChangesCount: @@ -623,24 +620,26 @@ withEachNg1Version(() => { `); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - const nodes = element.querySelectorAll('ng2'); - const expectedTextWith = (value: string) => - `ngOnChangesCount: 1 | firstChangesCount: 1 | initialValue: ${value}`; + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const nodes = element.querySelectorAll('ng2'); + const expectedTextWith = (value: string) => + `ngOnChangesCount: 1 | firstChangesCount: 1 | initialValue: ${value}`; - expect(multiTrim(nodes[0].textContent)).toBe(expectedTextWith('foo')); - expect(multiTrim(nodes[1].textContent)).toBe(expectedTextWith('bar')); - expect(multiTrim(nodes[2].textContent)).toBe(expectedTextWith('baz')); - expect(multiTrim(nodes[3].textContent)).toBe(expectedTextWith('qux')); - }); - })); + expect(multiTrim(nodes[0].textContent)).toBe(expectedTextWith('foo')); + expect(multiTrim(nodes[1].textContent)).toBe(expectedTextWith('bar')); + expect(multiTrim(nodes[2].textContent)).toBe(expectedTextWith('baz')); + expect(multiTrim(nodes[3].textContent)).toBe(expectedTextWith('qux')); + }); - it('should bind to ng-model', waitForAsync(() => { - const ng1Module = angular.module_('ng1', []).run(($rootScope: angular.IScope) => { - $rootScope['modelA'] = 'A'; - }); + it('should bind to ng-model', async () => { + const ng1Module = angular.module_('ng1', []).run([ + $ROOT_SCOPE, + ($rootScope: angular.IScope) => { + $rootScope['modelA'] = 'A'; + }, + ]); - let ng2Instance: Ng2; + let ng2Instance!: Ng2; @Component({ selector: 'ng2', template: '{{_value}}', @@ -681,33 +680,30 @@ withEachNg1Version(() => { ngDoBootstrap() {} } - platformBrowserDynamic() - .bootstrapModule(Ng2Module) - .then((ref) => { - const adapter = ref.injector.get(UpgradeModule) as UpgradeModule; - adapter.bootstrap(element, [ng1Module.name]); - const $rootScope = adapter.$injector.get('$rootScope'); + const ref = await platformBrowserDynamic().bootstrapModule(Ng2Module); + const adapter = ref.injector.get(UpgradeModule) as UpgradeModule; + adapter.bootstrap(element, [ng1Module.name]); + const $rootScope = adapter.$injector.get('$rootScope'); - expect(multiTrim(document.body.textContent)).toEqual('A | A'); + expect(multiTrim(document.body.textContent)).toEqual('A | A'); - $rootScope.modelA = 'B'; - $rootScope.$apply(); - expect(multiTrim(document.body.textContent)).toEqual('B | B'); + $rootScope.modelA = 'B'; + $rootScope.$apply(); + expect(multiTrim(document.body.textContent)).toEqual('B | B'); - ng2Instance.doChange('C'); - expect($rootScope.modelA).toBe('C'); - expect(multiTrim(document.body.textContent)).toEqual('C | C'); + ng2Instance.doChange('C'); + expect($rootScope.modelA).toBe('C'); + expect(multiTrim(document.body.textContent)).toEqual('C | C'); - const downgradedElement = document.body.querySelector('ng2'); - expect(downgradedElement.classList.contains('ng-touched')).toBe(false); + const downgradedElement = document.body.querySelector('ng2'); + expect(downgradedElement.classList.contains('ng-touched')).toBe(false); - ng2Instance.doTouch(); - $rootScope.$apply(); - expect(downgradedElement.classList.contains('ng-touched')).toBe(true); - }); - })); + ng2Instance.doTouch(); + $rootScope.$apply(); + expect(downgradedElement.classList.contains('ng-touched')).toBe(true); + }); - it('should properly run cleanup when ng1 directive is destroyed', waitForAsync(() => { + it('should properly run cleanup when ng1 directive is destroyed', async () => { let destroyed = false; @Component({ selector: 'ng2', @@ -733,46 +729,41 @@ withEachNg1Version(() => { }) .directive('ng2', downgradeComponent({component: Ng2Component})); const element = html(''); - platformBrowserDynamic() - .bootstrapModule(Ng2Module) - .then((ref) => { - const adapter = ref.injector.get(UpgradeModule) as UpgradeModule; - adapter.bootstrap(element, [ng1Module.name]); + const ref = await platformBrowserDynamic().bootstrapModule(Ng2Module); + const adapter = ref.injector.get(UpgradeModule) as UpgradeModule; + adapter.bootstrap(element, [ng1Module.name]); - const ng2Element = angular.element(element.querySelector('ng2') as Element); - const ng2Descendants = Array.from(element.querySelectorAll('ng2 li')).map( - angular.element, - ); - let ng2ElementDestroyed = false; - let ng2DescendantsDestroyed = [false, false]; + const ng2Element = angular.element(element.querySelector('ng2') as Element); + const ng2Descendants = Array.from(element.querySelectorAll('ng2 li')).map(angular.element); + let ng2ElementDestroyed = false; + let ng2DescendantsDestroyed = [false, false]; - ng2Element.data!('test', 42); - ng2Descendants.forEach((elem, i) => elem.data!('test', i)); - ng2Element.on!('$destroy', () => (ng2ElementDestroyed = true)); - ng2Descendants.forEach((elem, i) => - elem.on!('$destroy', () => (ng2DescendantsDestroyed[i] = true)), - ); + ng2Element.data!('test', 42); + ng2Descendants.forEach((elem, i) => elem.data!('test', i)); + ng2Element.on!('$destroy', () => (ng2ElementDestroyed = true)); + ng2Descendants.forEach((elem, i) => + elem.on!('$destroy', () => (ng2DescendantsDestroyed[i] = true)), + ); - expect(element.textContent).toBe('test1test2'); - expect(destroyed).toBe(false); - expect(ng2Element.data!('test')).toBe(42); - ng2Descendants.forEach((elem, i) => expect(elem.data!('test')).toBe(i)); - expect(ng2ElementDestroyed).toBe(false); - expect(ng2DescendantsDestroyed).toEqual([false, false]); + expect(element.textContent).toBe('test1test2'); + expect(destroyed).toBe(false); + expect(ng2Element.data!('test')).toBe(42); + ng2Descendants.forEach((elem, i) => expect(elem.data!('test')).toBe(i)); + expect(ng2ElementDestroyed).toBe(false); + expect(ng2DescendantsDestroyed).toEqual([false, false]); - const $rootScope = adapter.$injector.get('$rootScope'); - $rootScope.$apply('destroyIt = true'); + const $rootScope = adapter.$injector.get('$rootScope'); + $rootScope.$apply('destroyIt = true'); - expect(element.textContent).toBe(''); - expect(destroyed).toBe(true); - expect(ng2Element.data!('test')).toBeUndefined(); - ng2Descendants.forEach((elem) => expect(elem.data!('test')).toBeUndefined()); - expect(ng2ElementDestroyed).toBe(true); - expect(ng2DescendantsDestroyed).toEqual([true, true]); - }); - })); + expect(element.textContent).toBe(''); + expect(destroyed).toBe(true); + expect(ng2Element.data!('test')).toBeUndefined(); + ng2Descendants.forEach((elem) => expect(elem.data!('test')).toBeUndefined()); + expect(ng2ElementDestroyed).toBe(true); + expect(ng2DescendantsDestroyed).toEqual([true, true]); + }); - it('should properly run cleanup with multiple levels of nesting', waitForAsync(() => { + it('should properly run cleanup with multiple levels of nesting', async () => { let destroyed = false; @Component({ @@ -823,18 +814,17 @@ withEachNg1Version(() => { const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(element.textContent).toBe('test'); - expect(destroyed).toBe(false); + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(element.textContent).toBe('test'); + expect(destroyed).toBe(false); - $apply(upgrade, 'destroyIt = true'); + $apply(upgrade, 'destroyIt = true'); - expect(element.textContent).toBe(''); - expect(destroyed).toBe(true); - }); - })); + expect(element.textContent).toBe(''); + expect(destroyed).toBe(true); + }); - it('should destroy the AngularJS app when `PlatformRef` is destroyed', waitForAsync(() => { + it('should destroy the AngularJS app when `PlatformRef` is destroyed', async () => { @Component({ selector: 'ng2', template: 'NG2', @@ -859,46 +849,45 @@ withEachNg1Version(() => { const element = html('
'); const platformRef = platformBrowserDynamic(); - platformRef.bootstrapModule(Ng2Module).then((ref) => { - const upgrade = ref.injector.get(UpgradeModule); - upgrade.bootstrap(element, [ng1Module.name]); + const ref = await platformRef.bootstrapModule(Ng2Module); + const upgrade = ref.injector.get(UpgradeModule); + upgrade.bootstrap(element, [ng1Module.name]); - const $rootScope: angular.IRootScopeService = upgrade.$injector.get($ROOT_SCOPE); - const rootScopeDestroySpy = spyOn($rootScope, '$destroy'); + const $rootScope: angular.IRootScopeService = upgrade.$injector.get($ROOT_SCOPE); + const rootScopeDestroySpy = spyOn($rootScope, '$destroy'); - const appElem = angular.element(element); - const ng1Elem = angular.element(element.querySelector('ng1') as Element); - const ng2Elem = angular.element(element.querySelector('ng2') as Element); - const ng2ChildElem = angular.element(element.querySelector('ng2 span') as Element); + const appElem = angular.element(element); + const ng1Elem = angular.element(element.querySelector('ng1') as Element); + const ng2Elem = angular.element(element.querySelector('ng2') as Element); + const ng2ChildElem = angular.element(element.querySelector('ng2 span') as Element); - // Attach data to all elements. - appElem.data!('testData', 1); - ng1Elem.data!('testData', 2); - ng2Elem.data!('testData', 3); - ng2ChildElem.data!('testData', 4); + // Attach data to all elements. + appElem.data!('testData', 1); + ng1Elem.data!('testData', 2); + ng2Elem.data!('testData', 3); + ng2ChildElem.data!('testData', 4); - // Verify data can be retrieved. - expect(appElem.data!('testData')).toBe(1); - expect(ng1Elem.data!('testData')).toBe(2); - expect(ng2Elem.data!('testData')).toBe(3); - expect(ng2ChildElem.data!('testData')).toBe(4); + // Verify data can be retrieved. + expect(appElem.data!('testData')).toBe(1); + expect(ng1Elem.data!('testData')).toBe(2); + expect(ng2Elem.data!('testData')).toBe(3); + expect(ng2ChildElem.data!('testData')).toBe(4); - expect(rootScopeDestroySpy).not.toHaveBeenCalled(); + expect(rootScopeDestroySpy).not.toHaveBeenCalled(); - // Destroy `PlatformRef`. - platformRef.destroy(); + // Destroy `PlatformRef`. + platformRef.destroy(); - // Verify `$rootScope` has been destroyed and data has been cleaned up. - expect(rootScopeDestroySpy).toHaveBeenCalled(); + // Verify `$rootScope` has been destroyed and data has been cleaned up. + expect(rootScopeDestroySpy).toHaveBeenCalled(); - expect(appElem.data!('testData')).toBeUndefined(); - expect(ng1Elem.data!('testData')).toBeUndefined(); - expect(ng2Elem.data!('testData')).toBeUndefined(); - expect(ng2ChildElem.data!('testData')).toBeUndefined(); - }); - })); + expect(appElem.data!('testData')).toBeUndefined(); + expect(ng1Elem.data!('testData')).toBeUndefined(); + expect(ng2Elem.data!('testData')).toBeUndefined(); + expect(ng2ChildElem.data!('testData')).toBeUndefined(); + }); - it('should work when compiled outside the dom (by fallback to the root ng2.injector)', waitForAsync(() => { + it('should work when compiled outside the dom (by fallback to the root ng2.injector)', async () => { @Component({ selector: 'ng2', template: 'test', @@ -936,15 +925,14 @@ withEachNg1Version(() => { .directive('ng2', downgradeComponent({component: Ng2Component})); const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - // the fact that the body contains the correct text means that the - // downgraded component was able to access the moduleInjector - // (since there is no other injector in this system) - expect(multiTrim(document.body.textContent)).toEqual('test'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + // the fact that the body contains the correct text means that the + // downgraded component was able to access the moduleInjector + // (since there is no other injector in this system) + expect(multiTrim(document.body.textContent)).toEqual('test'); + }); - it('should allow attribute selectors for downgraded components', waitForAsync(() => { + it('should allow attribute selectors for downgraded components', async () => { @Component({ selector: '[itWorks]', template: 'It works', @@ -964,12 +952,11 @@ withEachNg1Version(() => { const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(document.body.textContent)).toBe('It works'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toBe('It works'); + }); - it('should allow attribute selectors for components in ng2', waitForAsync(() => { + it('should allow attribute selectors for components in ng2', async () => { @Component({ selector: '[itWorks]', template: 'It works', @@ -1000,12 +987,11 @@ withEachNg1Version(() => { const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(document.body.textContent)).toBe('It works!'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toBe('It works!'); + }); - it('should respect hierarchical dependency injection for ng2', waitForAsync(() => { + it('should respect hierarchical dependency injection for ng2', async () => { @Component({ selector: 'parent', template: 'parent()', @@ -1038,12 +1024,11 @@ withEachNg1Version(() => { const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(document.body.textContent)).toBe('parent(child)'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toBe('parent(child)'); + }); - it('should be compiled synchronously, if possible', waitForAsync(() => { + it('should be compiled synchronously, if possible', async () => { @Component({ selector: 'ng2A', template: '', @@ -1074,13 +1059,12 @@ withEachNg1Version(() => { const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(element.textContent).toBe('Ng2 template'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(element.textContent).toBe('Ng2 template'); + }); - it('should work with ng2 lazy loaded components', waitForAsync(() => { - let componentInjector: Injector; + it('should work with ng2 lazy loaded components', async () => { + let componentInjector!: Injector; @Component({ selector: 'ng2', @@ -1122,22 +1106,21 @@ withEachNg1Version(() => { const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - const modInjector = upgrade.injector; - // Emulate the router lazy loading a module and creating a component - const compiler = modInjector.get(Compiler); - const modFactory = compiler.compileModuleSync(LazyLoadedModule); - const childMod = modFactory.create(modInjector); - const lazyCmp = createComponent(LazyLoadedComponent, { - environmentInjector: childMod.injector, - elementInjector: componentInjector, - }); - - expect(lazyCmp.instance.module.injector === childMod.injector).toBe(true); + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const modInjector = upgrade.injector; + // Emulate the router lazy loading a module and creating a component + const compiler = modInjector.get(Compiler); + const modFactory = compiler.compileModuleSync(LazyLoadedModule); + const childMod = modFactory.create(modInjector); + const lazyCmp = createComponent(LazyLoadedComponent, { + environmentInjector: childMod.injector, + elementInjector: componentInjector, }); - })); - it('should throw if `downgradedModule` is specified', waitForAsync(() => { + expect(lazyCmp.instance.module.injector === childMod.injector).toBe(true); + }); + + it('should throw if `downgradedModule` is specified', async () => { @Component({ selector: 'ng2', template: '', @@ -1160,7 +1143,7 @@ withEachNg1Version(() => { const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then( + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then( () => { throw new Error('Expected bootstraping to fail.'); }, @@ -1172,14 +1155,14 @@ withEachNg1Version(() => { "downgrading more than one Angular module (via 'downgradeModule()').", ), ); - })); + }); }); describe('standalone', () => { beforeEach(() => destroyPlatform()); afterEach(() => destroyPlatform()); - it('should downgrade a standalone component using NgModule APIs', waitForAsync(() => { + it('should downgrade a standalone component using NgModule APIs', async () => { @Component({ selector: 'ng2', template: 'Hi from Angular!', @@ -1199,9 +1182,8 @@ withEachNg1Version(() => { } const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(element.textContent).toBe('Hi from Angular!'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(element.textContent).toBe('Hi from Angular!'); + }); }); }); diff --git a/packages/upgrade/static/test/integration/downgrade_module_spec.ts b/packages/upgrade/static/test/integration/downgrade_module_spec.ts index d02f5872222..d709ae68a7f 100644 --- a/packages/upgrade/static/test/integration/downgrade_module_spec.ts +++ b/packages/upgrade/static/test/integration/downgrade_module_spec.ts @@ -34,9 +34,9 @@ import { Type, ViewRef, } from '@angular/core'; -import {fakeAsync, tick, 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, downgradeModule, UpgradeComponent} from '../../../static'; import * as angular from '../../../src/common/src/angular1'; @@ -60,7 +60,7 @@ withEachNg1Version(() => { beforeEach(() => destroyPlatform()); afterEach(() => destroyPlatform()); - it('should support multiple downgraded modules', waitForAsync(() => { + it('should support multiple downgraded modules', async () => { @Component({ selector: 'ng2A', template: 'a', @@ -124,10 +124,11 @@ withEachNg1Version(() => { angular.bootstrap(element, [ng1Module.name]); // Wait for the module to be bootstrapped. - setTimeout(() => expect(element.textContent).toBe('a | b')); - })); + await timeout(); + expect(element.textContent).toBe('a | b'); + }); - it('should support downgrading modules by providing NgModule class to `downgradeModule` call', waitForAsync(() => { + it('should support downgrading modules by providing NgModule class to `downgradeModule` call', async () => { @Component({ selector: 'ng2A', template: 'a', @@ -183,10 +184,11 @@ withEachNg1Version(() => { angular.bootstrap(element, [ng1Module.name]); // Wait for the module to be bootstrapped. - setTimeout(() => expect(element.textContent).toBe('a | b')); - })); + await timeout(); + expect(element.textContent).toBe('a | b'); + }); - it('should support nesting components from different downgraded modules', waitForAsync(() => { + it('should support nesting components from different downgraded modules', async () => { @Directive({ selector: 'ng1A', standalone: false, @@ -264,20 +266,19 @@ withEachNg1Version(() => { const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; // Wait for module A to be bootstrapped. - setTimeout(() => { - // Wait for the upgraded component's `ngOnInit()`. - setTimeout(() => { - expect(element.textContent).toBe('ng2A(ng1A())'); + await timeout(); + // Wait for the upgraded component's `ngOnInit()`. + await timeout(); + expect(element.textContent).toBe('ng2A(ng1A())'); - $rootScope.$apply('showB = true'); + $rootScope.$apply('showB = true'); - // Wait for module B to be bootstrapped. - setTimeout(() => expect(element.textContent).toBe('ng2A(ng1A(ng2B))')); - }); - }); - })); + // Wait for module B to be bootstrapped. + await timeout(); + expect(element.textContent).toBe('ng2A(ng1A(ng2B))'); + }); - it('should support nesting components from different downgraded modules (via projection)', waitForAsync(() => { + it('should support nesting components from different downgraded modules (via projection)', async () => { @Component({ selector: 'ng2A', template: 'ng2A()', @@ -344,17 +345,17 @@ withEachNg1Version(() => { const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; // Wait for module A to be bootstrapped. - setTimeout(() => { - expect(element.textContent).toBe('ng2A()'); + await timeout(); + expect(element.textContent).toBe('ng2A()'); - $rootScope.$apply('showB = true'); + $rootScope.$apply('showB = true'); - // Wait for module B to be bootstrapped. - setTimeout(() => expect(element.textContent).toBe('ng2A(ng2B)')); - }); - })); + // Wait for module B to be bootstrapped. + await timeout(); + expect(element.textContent).toBe('ng2A(ng2B)'); + }); - it('should support manually setting up a root module for all downgraded modules', fakeAsync(() => { + it('should support manually setting up a root module for all downgraded modules', async () => { @Injectable({providedIn: 'root'}) class CounterService { private static counter = 0; @@ -447,23 +448,26 @@ withEachNg1Version(() => { const $injector = angular.bootstrap(element, [ng1Module.name]); const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; - tick(); // Wait for module A to be bootstrapped. + await timeout(); // Wait for module A to be bootstrapped. + await timeout(); // Wait for `$evalAsync()` to run change detection. expect(multiTrim(element.textContent)).toBe('ng2A(Counter:1 | )'); // Nested component B should use the same `CounterService` instance. $rootScope.$apply('showB1 = true'); - tick(); // Wait for module B to be bootstrapped. + await timeout(); // Wait for module B to be bootstrapped. + await timeout(); // Wait for `$evalAsync()` to run change detection. expect(multiTrim(element.children[0].textContent)).toBe('ng2A(Counter:1 | Counter:1)'); // Top-level component B should use the same `CounterService` instance. $rootScope.$apply('showB2 = true'); - tick(); + await timeout(); + await timeout(); expect(multiTrim(element.children[1].textContent)).toBe('Counter:1'); - })); + }); - it('should correctly traverse the injector tree of downgraded components', waitForAsync(() => { + it('should correctly traverse the injector tree of downgraded components', async () => { @Component({ selector: 'ng2A', template: 'ng2A()', @@ -532,24 +536,23 @@ withEachNg1Version(() => { const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; // Wait for the module to be bootstrapped. - setTimeout(() => { - expect(multiTrim(element.textContent)).toBe('ng2A()'); + await timeout(); + expect(multiTrim(element.textContent)).toBe('ng2A()'); - // Nested component B. - $rootScope.$apply('showB1 = true'); - expect(multiTrim(element.children[0].textContent)).toBe( - 'ng2A( FOO:CompB-foo BAR:CompA-bar BAZ:Mod-baz QUX:Plat-qux )', - ); + // Nested component B. + $rootScope.$apply('showB1 = true'); + expect(multiTrim(element.children[0].textContent)).toBe( + 'ng2A( FOO:CompB-foo BAR:CompA-bar BAZ:Mod-baz QUX:Plat-qux )', + ); - // Standalone component B. - $rootScope.$apply('showB2 = true'); - expect(multiTrim(element.children[1].textContent)).toBe( - 'FOO:CompB-foo BAR:Mod-bar BAZ:Mod-baz QUX:Plat-qux', - ); - }); - })); + // Standalone component B. + $rootScope.$apply('showB2 = true'); + expect(multiTrim(element.children[1].textContent)).toBe( + 'FOO:CompB-foo BAR:Mod-bar BAZ:Mod-baz QUX:Plat-qux', + ); + }); - it('should correctly traverse the injector tree of downgraded components (from different modules)', waitForAsync(() => { + it('should correctly traverse the injector tree of downgraded components (from different modules)', async () => { @Component({ selector: 'ng2A', template: 'ng2A()', @@ -652,31 +655,29 @@ withEachNg1Version(() => { const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; // Wait for module A to be bootstrapped. - setTimeout(() => { - expect(multiTrim(element.textContent)).toBe('ng2A()'); + await timeout(); + expect(multiTrim(element.textContent)).toBe('ng2A()'); - // Nested component B. - $rootScope.$apply('showB1 = true'); + // Nested component B. + $rootScope.$apply('showB1 = true'); - // Wait for module B to be bootstrapped. - setTimeout(() => { - // It is debatable, whether the order of traversal should be: - // CompB > CompA > ModB > ModA > Plat (similar to how lazy-loaded components - // work) - expect(multiTrim(element.children[0].textContent)).toBe( - 'ng2A( FOO:CompB-foo BAR:CompA-bar BAZ:ModB-baz QUX:Plat-qux QUUX:Plat-quux )', - ); + // Wait for module B to be bootstrapped. + await timeout(); + // It is debatable, whether the order of traversal should be: + // CompB > CompA > ModB > ModA > Plat (similar to how lazy-loaded components + // work) + expect(multiTrim(element.children[0].textContent)).toBe( + 'ng2A( FOO:CompB-foo BAR:CompA-bar BAZ:ModB-baz QUX:Plat-qux QUUX:Plat-quux )', + ); - // Standalone component B. - $rootScope.$apply('showB2 = true'); - expect(multiTrim(element.children[1].textContent)).toBe( - 'FOO:CompB-foo BAR:ModB-bar BAZ:ModB-baz QUX:Plat-qux QUUX:Plat-quux', - ); - }); - }); - })); + // Standalone component B. + $rootScope.$apply('showB2 = true'); + expect(multiTrim(element.children[1].textContent)).toBe( + 'FOO:CompB-foo BAR:ModB-bar BAZ:ModB-baz QUX:Plat-qux QUUX:Plat-quux', + ); + }); - it('should support downgrading a component and propagate inputs', waitForAsync(() => { + it('should support downgrading a component and propagate inputs', async () => { @Component({ selector: 'ng2A', template: 'a({{ value }}) | ', @@ -732,15 +733,15 @@ withEachNg1Version(() => { expect(() => $injector.get(INJECTOR_KEY)).toThrowError(); // Wait for the module to be bootstrapped. - setTimeout(() => { - expect(() => $injector.get(INJECTOR_KEY)).not.toThrow(); + await timeout(); + expect(() => $injector.get(INJECTOR_KEY)).not.toThrow(); - // Wait for `$evalAsync()` to propagate inputs. - setTimeout(() => expect(element.textContent).toBe('a(1) | b(1)')); - }); - })); + // Wait for `$evalAsync()` to propagate inputs. + await timeout(); + expect(element.textContent).toBe('a(1) | b(1)'); + }); - it('should support using an upgraded service', waitForAsync(() => { + it('should support using an upgraded service', async () => { @Injectable() class Ng2Service { constructor(@Inject('ng1Value') private ng1Value: string) {} @@ -797,15 +798,15 @@ withEachNg1Version(() => { expect(() => $injector.get(INJECTOR_KEY)).toThrowError(); // Wait for the module to be bootstrapped. - setTimeout(() => { - expect(() => $injector.get(INJECTOR_KEY)).not.toThrow(); + await timeout(); + expect(() => $injector.get(INJECTOR_KEY)).not.toThrow(); - // Wait for `$evalAsync()` to propagate inputs. - setTimeout(() => expect(element.textContent).toBe('foo-bar')); - }); - })); + // Wait for `$evalAsync()` to propagate inputs. + await timeout(); + expect(element.textContent).toBe('foo-bar'); + }); - it('should create components inside the Angular zone', waitForAsync(() => { + it('should create components inside the Angular zone', async () => { @Component({ selector: 'ng2', template: 'In the zone: {{ inTheZone }}', @@ -839,13 +840,13 @@ withEachNg1Version(() => { angular.bootstrap(element, [ng1Module.name]); // Wait for the module to be bootstrapped. - setTimeout(() => { - // Wait for `$evalAsync()` to propagate inputs. - setTimeout(() => expect(element.textContent).toBe('In the zone: true')); - }); - })); + await timeout(); + // Wait for `$evalAsync()` to propagate inputs. + await timeout(); + expect(element.textContent).toBe('In the zone: true'); + }); - it('should destroy components inside the Angular zone', waitForAsync(() => { + it('should destroy components inside the Angular zone', async () => { let destroyedInTheZone = false; @Component({ @@ -881,14 +882,13 @@ withEachNg1Version(() => { const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; // Wait for the module to be bootstrapped. - setTimeout(() => { - $rootScope.$apply('hideNg2 = true'); - expect(destroyedInTheZone).toBe(true); - }); - })); + await timeout(); + $rootScope.$apply('hideNg2 = true'); + expect(destroyedInTheZone).toBe(true); + }); - it('should propagate input changes inside the Angular zone', waitForAsync(() => { - let ng2Component: Ng2Component; + it('should propagate input changes inside the Angular zone', async () => { + let ng2Component!: Ng2Component; @Component({ selector: 'ng2', @@ -933,30 +933,28 @@ withEachNg1Version(() => { const $injector = angular.bootstrap(element, [ng1Module.name]); const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; - setTimeout(() => { - // Wait for the module to be bootstrapped. - setTimeout(() => { - // Wait for `$evalAsync()` to propagate inputs. - const expectToBeInNgZone = () => expect(NgZone.isInAngularZone()).toBe(true); - const changesSpy = spyOn(ng2Component, 'ngOnChanges').and.callFake(expectToBeInNgZone); + // Wait for the module to be bootstrapped. + await timeout(); + // Wait for `$evalAsync()` to propagate inputs. + await timeout(); + const expectToBeInNgZone = () => expect(NgZone.isInAngularZone()).toBe(true); + const changesSpy = spyOn(ng2Component, 'ngOnChanges').and.callFake(expectToBeInNgZone); - expect(ng2Component.attrInput).toBe('bar'); - expect(ng2Component.propInput).toBe('bar'); + expect(ng2Component.attrInput).toBe('bar'); + expect(ng2Component.propInput).toBe('bar'); - $rootScope.$apply('attrVal = "baz"'); - expect(ng2Component.attrInput).toBe('baz'); - expect(ng2Component.propInput).toBe('bar'); - expect(changesSpy).toHaveBeenCalledTimes(1); + $rootScope.$apply('attrVal = "baz"'); + expect(ng2Component.attrInput).toBe('baz'); + expect(ng2Component.propInput).toBe('bar'); + expect(changesSpy).toHaveBeenCalledTimes(1); - $rootScope.$apply('propVal = "qux"'); - expect(ng2Component.attrInput).toBe('baz'); - expect(ng2Component.propInput).toBe('qux'); - expect(changesSpy).toHaveBeenCalledTimes(2); - }); - }); - })); + $rootScope.$apply('propVal = "qux"'); + expect(ng2Component.attrInput).toBe('baz'); + expect(ng2Component.propInput).toBe('qux'); + expect(changesSpy).toHaveBeenCalledTimes(2); + }); - it('should create and destroy nested, asynchronously instantiated components inside the Angular zone', waitForAsync(() => { + it('should create and destroy nested, asynchronously instantiated components inside the Angular zone', async () => { let createdInTheZone = false; let destroyedInTheZone = false; @@ -1005,22 +1003,21 @@ withEachNg1Version(() => { const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; // Wait for the module to be bootstrapped. - setTimeout(() => { - // Create nested component asynchronously. - expect(createdInTheZone).toBe(false); + await timeout(); + // Create nested component asynchronously. + expect(createdInTheZone).toBe(false); - $rootScope.$apply('showNg2 = true'); - expect(createdInTheZone).toBe(true); + $rootScope.$apply('showNg2 = true'); + expect(createdInTheZone).toBe(true); - // Destroy nested component asynchronously. - expect(destroyedInTheZone).toBe(false); + // Destroy nested component asynchronously. + expect(destroyedInTheZone).toBe(false); - $rootScope.$apply('showNg2 = false'); - expect(destroyedInTheZone).toBe(true); - }); - })); + $rootScope.$apply('showNg2 = false'); + expect(destroyedInTheZone).toBe(true); + }); - it('should wire up the component for change detection', waitForAsync(() => { + it('should wire up the component for change detection', async () => { @Component({ selector: 'ng2', template: '{{ count }}', @@ -1053,23 +1050,21 @@ withEachNg1Version(() => { const element = html(''); angular.bootstrap(element, [ng1Module.name]); - setTimeout(() => { - // Wait for the module to be bootstrapped. - setTimeout(() => { - // Wait for `$evalAsync()` to propagate inputs. - const button = element.querySelector('button')!; - expect(element.textContent).toBe('0'); + // Wait for the module to be bootstrapped. + await timeout(); + // Wait for `$evalAsync()` to propagate inputs. + await timeout(); + const button = element.querySelector('button')!; + expect(element.textContent).toBe('0'); - button.click(); - expect(element.textContent).toBe('1'); + button.click(); + expect(element.textContent).toBe('1'); - button.click(); - expect(element.textContent).toBe('2'); - }); - }); - })); + button.click(); + expect(element.textContent).toBe('2'); + }); - it('should wire up nested, asynchronously instantiated components for change detection', waitForAsync(() => { + it('should wire up nested, asynchronously instantiated components for change detection', async () => { @Component({ selector: 'test', template: '{{ count }}', @@ -1113,24 +1108,23 @@ withEachNg1Version(() => { const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; // Wait for the module to be bootstrapped. - setTimeout(() => { - // Create nested component asynchronously. - $rootScope.$apply('showNg2 = true'); - const button = element.querySelector('button')!; + await timeout(); + // Create nested component asynchronously. + $rootScope.$apply('showNg2 = true'); + const button = element.querySelector('button')!; - expect(element.textContent).toBe('0'); + expect(element.textContent).toBe('0'); - button.click(); - expect(element.textContent).toBe('1'); + button.click(); + expect(element.textContent).toBe('1'); - button.click(); - expect(element.textContent).toBe('2'); - }); - })); + button.click(); + expect(element.textContent).toBe('2'); + }); - it('should run the lifecycle hooks in the correct order', waitForAsync(() => { + it('should run the lifecycle hooks in the correct order', async () => { const logs: string[] = []; - let rootScope: angular.IRootScopeService; + let rootScope!: angular.IRootScopeService; @Component({ selector: 'ng2', @@ -1209,112 +1203,106 @@ withEachNg1Version(() => { const element = html('
Content
'); angular.bootstrap(element, [ng1Module.name]); - setTimeout(() => { - // Wait for the module to be bootstrapped. - setTimeout(() => { - // Wait for `$evalAsync()` to propagate inputs. - const button = element.querySelector('button')!; + // Wait for the module to be bootstrapped. + await timeout(); + // Wait for `$evalAsync()` to propagate inputs. + await timeout(); + const button = element.querySelector('button')!; - // Once initialized. - expect(multiTrim(element.textContent)).toBe('bar Content'); - expect(logs).toEqual([ - // `ngOnChanges()` call triggered directly through the `inputChanges` - // $watcher. - 'OnChanges(bar)', - // Initial CD triggered directly through the `detectChanges()` or - // `inputChanges` - // $watcher (for `propagateDigest` true/false respectively). - 'OnInit(bar)', - 'DoCheck(bar)', - 'AfterContentInit(bar)', - 'AfterContentChecked(bar)', - 'AfterViewInit(bar)', - 'AfterViewChecked(bar)', - ...(propagateDigest - ? [ - // CD triggered directly through the `detectChanges()` $watcher (2nd - // $digest). - 'DoCheck(bar)', - 'AfterContentChecked(bar)', - 'AfterViewChecked(bar)', - ] - : []), - // CD triggered due to entering/leaving the NgZone (in `downgradeFn()`). - 'DoCheck(bar)', - 'AfterContentChecked(bar)', - 'AfterViewChecked(bar)', - ]); - logs.length = 0; + // Once initialized. + expect(multiTrim(element.textContent)).toBe('bar Content'); + expect(logs).toEqual([ + // `ngOnChanges()` call triggered directly through the `inputChanges` + // $watcher. + 'OnChanges(bar)', + // Initial CD triggered directly through the `detectChanges()` or + // `inputChanges` + // $watcher (for `propagateDigest` true/false respectively). + 'OnInit(bar)', + 'DoCheck(bar)', + 'AfterContentInit(bar)', + 'AfterContentChecked(bar)', + 'AfterViewInit(bar)', + 'AfterViewChecked(bar)', + ...(propagateDigest + ? [ + // CD triggered directly through the `detectChanges()` $watcher (2nd + // $digest). + 'DoCheck(bar)', + 'AfterContentChecked(bar)', + 'AfterViewChecked(bar)', + ] + : []), + // CD triggered due to entering/leaving the NgZone (in `downgradeFn()`). + 'DoCheck(bar)', + 'AfterContentChecked(bar)', + 'AfterViewChecked(bar)', + ]); + logs.length = 0; - // Change inputs and run `$digest`. - rootScope.$apply('value = "baz"'); - expect(multiTrim(element.textContent)).toBe('baz Content'); - expect(logs).toEqual([ - // `ngOnChanges()` call triggered directly through the `inputChanges` - // $watcher. - 'OnChanges(baz)', - // `propagateDigest: true` (3 CD runs): - // - CD triggered due to entering/leaving the NgZone (in `inputChanges` - // $watcher). - // - CD triggered directly through the `detectChanges()` $watcher. - // - CD triggered due to entering/leaving the NgZone (in `detectChanges` - // $watcher). - // `propagateDigest: false` (2 CD runs): - // - CD triggered directly through the `inputChanges` $watcher. - // - CD triggered due to entering/leaving the NgZone (in `inputChanges` - // $watcher). - 'DoCheck(baz)', - 'AfterContentChecked(baz)', - 'AfterViewChecked(baz)', - 'DoCheck(baz)', - 'AfterContentChecked(baz)', - 'AfterViewChecked(baz)', - ...(propagateDigest - ? ['DoCheck(baz)', 'AfterContentChecked(baz)', 'AfterViewChecked(baz)'] - : []), - ]); - logs.length = 0; + // Change inputs and run `$digest`. + rootScope.$apply('value = "baz"'); + expect(multiTrim(element.textContent)).toBe('baz Content'); + expect(logs).toEqual([ + // `ngOnChanges()` call triggered directly through the `inputChanges` + // $watcher. + 'OnChanges(baz)', + // `propagateDigest: true` (3 CD runs): + // - CD triggered due to entering/leaving the NgZone (in `inputChanges` + // $watcher). + // - CD triggered directly through the `detectChanges()` $watcher. + // - CD triggered due to entering/leaving the NgZone (in `detectChanges` + // $watcher). + // `propagateDigest: false` (2 CD runs): + // - CD triggered directly through the `inputChanges` $watcher. + // - CD triggered due to entering/leaving the NgZone (in `inputChanges` + // $watcher). + 'DoCheck(baz)', + 'AfterContentChecked(baz)', + 'AfterViewChecked(baz)', + 'DoCheck(baz)', + 'AfterContentChecked(baz)', + 'AfterViewChecked(baz)', + ...(propagateDigest + ? ['DoCheck(baz)', 'AfterContentChecked(baz)', 'AfterViewChecked(baz)'] + : []), + ]); + logs.length = 0; - // Run `$digest` (without changing inputs). - rootScope.$digest(); - expect(multiTrim(element.textContent)).toBe('baz Content'); - expect(logs).toEqual( - propagateDigest - ? [ - // CD triggered directly through the `detectChanges()` $watcher. - 'DoCheck(baz)', - 'AfterContentChecked(baz)', - 'AfterViewChecked(baz)', - // CD triggered due to entering/leaving the NgZone (in the above - // $watcher). - 'DoCheck(baz)', - 'AfterContentChecked(baz)', - 'AfterViewChecked(baz)', - ] - : [], - ); - logs.length = 0; + // Run `$digest` (without changing inputs). + rootScope.$digest(); + expect(multiTrim(element.textContent)).toBe('baz Content'); + expect(logs).toEqual( + propagateDigest + ? [ + // CD triggered directly through the `detectChanges()` $watcher. + 'DoCheck(baz)', + 'AfterContentChecked(baz)', + 'AfterViewChecked(baz)', + // CD triggered due to entering/leaving the NgZone (in the above + // $watcher). + 'DoCheck(baz)', + 'AfterContentChecked(baz)', + 'AfterViewChecked(baz)', + ] + : [], + ); + logs.length = 0; - // Trigger change detection (without changing inputs). - button.click(); - expect(multiTrim(element.textContent)).toBe('qux Content'); - expect(logs).toEqual([ - 'DoCheck(qux)', - 'AfterContentChecked(qux)', - 'AfterViewChecked(qux)', - ]); - logs.length = 0; + // Trigger change detection (without changing inputs). + button.click(); + expect(multiTrim(element.textContent)).toBe('qux Content'); + expect(logs).toEqual(['DoCheck(qux)', 'AfterContentChecked(qux)', 'AfterViewChecked(qux)']); + logs.length = 0; - // Destroy the component. - rootScope.$apply('hideNg2 = true'); - expect(logs).toEqual(['OnDestroy(qux)']); - logs.length = 0; - }); - }); - })); + // Destroy the component. + rootScope.$apply('hideNg2 = true'); + expect(logs).toEqual(['OnDestroy(qux)']); + logs.length = 0; + }); - it('should detach hostViews from the ApplicationRef once destroyed', waitForAsync(() => { - let ng2Component: Ng2Component; + it('should detach hostViews from the ApplicationRef once destroyed', async () => { + let ng2Component!: Ng2Component; @Component({ selector: 'ng2', @@ -1350,25 +1338,22 @@ withEachNg1Version(() => { const $injector = angular.bootstrap(element, [ng1Module.name]); const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; - setTimeout(() => { - // Wait for the module to be bootstrapped. - setTimeout(() => { - // Wait for the hostView to be attached (during the `$digest`). - const hostView: ViewRef = ( - ng2Component.appRef.attachView as jasmine.Spy - ).calls.mostRecent().args[0]; + // Wait for the module to be bootstrapped. + await timeout(); + // Wait for the hostView to be attached (during the `$digest`). + await timeout(); + const hostView: ViewRef = (ng2Component.appRef.attachView as jasmine.Spy).calls.mostRecent() + .args[0]; - expect(hostView.destroyed).toBe(false); + expect(hostView.destroyed).toBe(false); - $rootScope.$apply('hideNg2 = true'); + $rootScope.$apply('hideNg2 = true'); - expect(hostView.destroyed).toBe(true); - expect(ng2Component.appRef.detachView).toHaveBeenCalledWith(hostView); - }); - }); - })); + expect(hostView.destroyed).toBe(true); + expect(ng2Component.appRef.detachView).toHaveBeenCalledWith(hostView); + }); - it('should properly run cleanup when a downgraded component is destroyed', waitForAsync(() => { + it('should properly run cleanup when a downgraded component is destroyed', async () => { let destroyed = false; @Component({ @@ -1403,41 +1388,38 @@ withEachNg1Version(() => { const $injector = angular.bootstrap(element, [ng1Module.name]); const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; - setTimeout(() => { - // Wait for the module to be bootstrapped. - const ng2Element = angular.element(element.querySelector('ng2') as Element); - const ng2Descendants = Array.from(element.querySelectorAll('ng2 li')).map( - angular.element, - ); - let ng2ElementDestroyed = false; - let ng2DescendantsDestroyed = [false, false]; + // Wait for the module to be bootstrapped. + await timeout(); + const ng2Element = angular.element(element.querySelector('ng2') as Element); + const ng2Descendants = Array.from(element.querySelectorAll('ng2 li')).map(angular.element); + let ng2ElementDestroyed = false; + let ng2DescendantsDestroyed = [false, false]; - ng2Element.data!('test', 42); - ng2Descendants.forEach((elem, i) => elem.data!('test', i)); - ng2Element.on!('$destroy', () => (ng2ElementDestroyed = true)); - ng2Descendants.forEach((elem, i) => - elem.on!('$destroy', () => (ng2DescendantsDestroyed[i] = true)), - ); + ng2Element.data!('test', 42); + ng2Descendants.forEach((elem, i) => elem.data!('test', i)); + ng2Element.on!('$destroy', () => (ng2ElementDestroyed = true)); + ng2Descendants.forEach((elem, i) => + elem.on!('$destroy', () => (ng2DescendantsDestroyed[i] = true)), + ); - expect(element.textContent).toBe('test1test2'); - expect(destroyed).toBe(false); - expect(ng2Element.data!('test')).toBe(42); - ng2Descendants.forEach((elem, i) => expect(elem.data!('test')).toBe(i)); - expect(ng2ElementDestroyed).toBe(false); - expect(ng2DescendantsDestroyed).toEqual([false, false]); + expect(element.textContent).toBe('test1test2'); + expect(destroyed).toBe(false); + expect(ng2Element.data!('test')).toBe(42); + ng2Descendants.forEach((elem, i) => expect(elem.data!('test')).toBe(i)); + expect(ng2ElementDestroyed).toBe(false); + expect(ng2DescendantsDestroyed).toEqual([false, false]); - $rootScope.$apply('hideNg2 = true'); + $rootScope.$apply('hideNg2 = true'); - expect(element.textContent).toBe(''); - expect(destroyed).toBe(true); - expect(ng2Element.data!('test')).toBeUndefined(); - ng2Descendants.forEach((elem) => expect(elem.data!('test')).toBeUndefined()); - expect(ng2ElementDestroyed).toBe(true); - expect(ng2DescendantsDestroyed).toEqual([true, true]); - }); - })); + expect(element.textContent).toBe(''); + expect(destroyed).toBe(true); + expect(ng2Element.data!('test')).toBeUndefined(); + ng2Descendants.forEach((elem) => expect(elem.data!('test')).toBeUndefined()); + expect(ng2ElementDestroyed).toBe(true); + expect(ng2DescendantsDestroyed).toEqual([true, true]); + }); - it('should only retrieve the Angular zone once (and cache it for later use)', fakeAsync(() => { + it('should only retrieve the Angular zone once (and cache it for later use)', async () => { let count = 0; let getNgZoneCount = 0; @@ -1483,8 +1465,9 @@ withEachNg1Version(() => { const $rootScope = $injector.get($ROOT_SCOPE) as angular.IRootScopeService; $rootScope.$apply('showNg2 = true'); - tick(0); // Wait for the module to be bootstrapped and `$evalAsync()` to - // propagate inputs. + // Wait for the module to be bootstrapped and `$evalAsync()` to propagate inputs. + await timeout(); + await timeout(); const injector = ($injector.get(LAZY_MODULE_REF) as LazyModuleRef).injector!; const injectorGet = injector.get; @@ -1499,14 +1482,14 @@ withEachNg1Version(() => { expect(element.textContent).toBe(''); $rootScope.$apply('showNg2 = true'); - tick(0); // Wait for `$evalAsync()` to propagate inputs. + await timeout(); // Wait for `$evalAsync()` to propagate inputs. expect(element.textContent).toBe('Count: 2 | In the zone: true'); $rootScope.$destroy(); - })); + }); - it("should give access to both injectors in the Angular module's constructor", waitForAsync(() => { - let $injectorFromNg2: angular.IInjectorService | null = null; + it("should give access to both injectors in the Angular module's constructor", async () => { + let $injectorFromNg2 = null as angular.IInjectorService | null; @Component({ selector: 'ng2', @@ -1540,10 +1523,11 @@ withEachNg1Version(() => { const $injectorFromNg1 = angular.bootstrap(element, [ng1Module.name]); // Wait for the module to be bootstrapped. - setTimeout(() => expect($injectorFromNg2).toBe($injectorFromNg1)); - })); + await timeout(); + expect($injectorFromNg2).toBe($injectorFromNg1); + }); - it('should destroy the AngularJS app when `PlatformRef` is destroyed', waitForAsync(() => { + it('should destroy the AngularJS app when `PlatformRef` is destroyed', async () => { @Component({ selector: 'ng2', template: 'NG2', @@ -1572,42 +1556,41 @@ withEachNg1Version(() => { const element = html('
'); const $injector = angular.bootstrap(element, [ng1Module.name]); - setTimeout(() => { - // Wait for the module to be bootstrapped. - const $rootScope: angular.IRootScopeService = $injector.get($ROOT_SCOPE); - const rootScopeDestroySpy = spyOn($rootScope, '$destroy'); + // Wait for the module to be bootstrapped. + await timeout(); + const $rootScope: angular.IRootScopeService = $injector.get($ROOT_SCOPE); + const rootScopeDestroySpy = spyOn($rootScope, '$destroy'); - const appElem = angular.element(element); - const ng1Elem = angular.element(element.querySelector('ng1') as Element); - const ng2Elem = angular.element(element.querySelector('ng2') as Element); - const ng2ChildElem = angular.element(element.querySelector('ng2 span') as Element); + const appElem = angular.element(element); + const ng1Elem = angular.element(element.querySelector('ng1') as Element); + const ng2Elem = angular.element(element.querySelector('ng2') as Element); + const ng2ChildElem = angular.element(element.querySelector('ng2 span') as Element); - // Attach data to all elements. - appElem.data!('testData', 1); - ng1Elem.data!('testData', 2); - ng2Elem.data!('testData', 3); - ng2ChildElem.data!('testData', 4); + // Attach data to all elements. + appElem.data!('testData', 1); + ng1Elem.data!('testData', 2); + ng2Elem.data!('testData', 3); + ng2ChildElem.data!('testData', 4); - // Verify data can be retrieved. - expect(appElem.data!('testData')).toBe(1); - expect(ng1Elem.data!('testData')).toBe(2); - expect(ng2Elem.data!('testData')).toBe(3); - expect(ng2ChildElem.data!('testData')).toBe(4); + // Verify data can be retrieved. + expect(appElem.data!('testData')).toBe(1); + expect(ng1Elem.data!('testData')).toBe(2); + expect(ng2Elem.data!('testData')).toBe(3); + expect(ng2ChildElem.data!('testData')).toBe(4); - expect(rootScopeDestroySpy).not.toHaveBeenCalled(); + expect(rootScopeDestroySpy).not.toHaveBeenCalled(); - // Destroy `PlatformRef`. - getPlatform()?.destroy(); + // Destroy `PlatformRef`. + getPlatform()?.destroy(); - // Verify `$rootScope` has been destroyed and data has been cleaned up. - expect(rootScopeDestroySpy).toHaveBeenCalled(); + // Verify `$rootScope` has been destroyed and data has been cleaned up. + expect(rootScopeDestroySpy).toHaveBeenCalled(); - expect(appElem.data!('testData')).toBeUndefined(); - expect(ng1Elem.data!('testData')).toBeUndefined(); - expect(ng2Elem.data!('testData')).toBeUndefined(); - expect(ng2ChildElem.data!('testData')).toBeUndefined(); - }); - })); + expect(appElem.data!('testData')).toBeUndefined(); + expect(ng1Elem.data!('testData')).toBeUndefined(); + expect(ng2Elem.data!('testData')).toBeUndefined(); + expect(ng2ChildElem.data!('testData')).toBeUndefined(); + }); describe('(common error)', () => { let Ng2CompA: Type; @@ -1668,7 +1651,7 @@ withEachNg1Version(() => { // Explicitly clean up after each test to prevent that. afterEach(() => setTempInjectorRef(null!)); - it('should throw if no downgraded module is included', waitForAsync(() => { + it('should throw if no downgraded module is included', async () => { const ng1Module = angular .module_('ng1', []) .value($EXCEPTION_HANDLER, errorSpy) @@ -1710,9 +1693,10 @@ withEachNg1Version(() => { ), '', ); - })); + await timeout(); + }); - it('should throw if the corresponding downgraded module is not included', waitForAsync(() => { + it('should throw if the corresponding downgraded module is not included', async () => { const ng1Module = angular .module_('ng1', [downModA]) .value($EXCEPTION_HANDLER, errorSpy) @@ -1746,9 +1730,10 @@ withEachNg1Version(() => { ), '', ); - })); + await timeout(); + }); - it('should throw if `downgradedModule` is not specified and there are multiple downgraded modules', waitForAsync(() => { + it('should throw if `downgradedModule` is not specified and there are multiple downgraded modules', async () => { const ng1Module = angular .module_('ng1', [downModA, downModB]) .value($EXCEPTION_HANDLER, errorSpy) @@ -1782,7 +1767,8 @@ withEachNg1Version(() => { ), '', ); - })); + await timeout(); + }); }); }); }); diff --git a/packages/upgrade/static/test/integration/examples_spec.ts b/packages/upgrade/static/test/integration/examples_spec.ts index 3078348fdf7..b8d4391d64f 100644 --- a/packages/upgrade/static/test/integration/examples_spec.ts +++ b/packages/upgrade/static/test/integration/examples_spec.ts @@ -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'; @@ -37,7 +36,7 @@ withEachNg1Version(() => { it('should have AngularJS loaded', () => expect(angular.getAngularJSGlobal().version.major).toBe(1)); - it('should verify UpgradeAdapter example', waitForAsync(() => { + it('should verify UpgradeAdapter example', async () => { // This is wrapping (upgrading) an AngularJS component to be used in an Angular // component @Directive({ @@ -94,9 +93,8 @@ withEachNg1Version(() => { const element = html('project'); // Let's use a helper function to make this simpler - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(element.textContent)).toBe('ng2[ng1[Hello World!](transclude)](project)'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('ng2[ng1[Hello World!](transclude)](project)'); + }); }); }); diff --git a/packages/upgrade/static/test/integration/injection_spec.ts b/packages/upgrade/static/test/integration/injection_spec.ts index 8f91bdd447a..b390e8349ef 100644 --- a/packages/upgrade/static/test/integration/injection_spec.ts +++ b/packages/upgrade/static/test/integration/injection_spec.ts @@ -7,7 +7,6 @@ */ import {destroyPlatform, InjectionToken, Injector, NgModule} from '@angular/core'; -import {waitForAsync} from '@angular/core/testing'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; @@ -28,7 +27,7 @@ withEachNg1Version(() => { beforeEach(() => destroyPlatform()); afterEach(() => destroyPlatform()); - it('should downgrade ng2 service to ng1', waitForAsync(() => { + it('should downgrade ng2 service to ng1', async () => { // Tokens used in ng2 to identify services const Ng2Service = new InjectionToken('ng2-service'); @@ -46,13 +45,17 @@ withEachNg1Version(() => { .module_('ng1Module', []) .factory('ng2Service', downgradeInjectable(Ng2Service)); - bootstrap(platformBrowserDynamic(), Ng2Module, html('
'), ng1Module).then((upgrade) => { - const ng1Injector = upgrade.$injector; - expect(ng1Injector.get('ng2Service')).toBe('ng2 service value'); - }); - })); + const upgrade = await bootstrap( + platformBrowserDynamic(), + Ng2Module, + html('
'), + ng1Module, + ); + const ng1Injector = upgrade.$injector; + expect(ng1Injector.get('ng2Service')).toBe('ng2 service value'); + }); - it('should upgrade ng1 service to ng2', waitForAsync(() => { + it('should upgrade ng1 service to ng2', async () => { // Tokens used in ng2 to identify services const Ng1Service = new InjectionToken('ng1-service'); @@ -75,13 +78,17 @@ withEachNg1Version(() => { // create the ng1 module that will import an ng2 service const ng1Module = angular.module_('ng1Module', []).value('ng1Service', 'ng1 service value'); - bootstrap(platformBrowserDynamic(), Ng2Module, html('
'), ng1Module).then((upgrade) => { - const ng2Injector = upgrade.injector; - expect(ng2Injector.get(Ng1Service)).toBe('ng1 service value'); - }); - })); + const upgrade = await bootstrap( + platformBrowserDynamic(), + Ng2Module, + html('
'), + ng1Module, + ); + const ng2Injector = upgrade.injector; + expect(ng2Injector.get(Ng1Service)).toBe('ng1 service value'); + }); - it('should initialize the upgraded injector before application run blocks are executed', waitForAsync(() => { + it('should initialize the upgraded injector before application run blocks are executed', async () => { let runBlockTriggered = false; const ng1Module = angular.module_('ng1Module', []).run([ @@ -97,12 +104,11 @@ withEachNg1Version(() => { ngDoBootstrap() {} } - bootstrap(platformBrowserDynamic(), Ng2Module, html('
'), ng1Module).then(() => { - expect(runBlockTriggered).toBeTruthy(); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, html('
'), ng1Module); + expect(runBlockTriggered).toBeTruthy(); + }); - it('should allow resetting angular at runtime', waitForAsync(() => { + it('should allow resetting angular at runtime', async () => { let wrappedBootstrapCalled = false; const n: any = getAngularJSGlobal(); @@ -126,9 +132,9 @@ withEachNg1Version(() => { const ng1Module = angular.module_('ng1Module', []); - bootstrap(platformBrowserDynamic(), Ng2Module, html('
'), ng1Module) - .then((upgrade) => expect(wrappedBootstrapCalled).toBe(true)) - .then(() => setAngularJSGlobal(n)); // Reset the AngularJS global. - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, html('
'), ng1Module); + expect(wrappedBootstrapCalled).toBe(true); + setAngularJSGlobal(n); // Reset the AngularJS global. + }); }); }); diff --git a/packages/upgrade/static/test/integration/testability_spec.ts b/packages/upgrade/static/test/integration/testability_spec.ts index fb8d566927b..596e13f8061 100644 --- a/packages/upgrade/static/test/integration/testability_spec.ts +++ b/packages/upgrade/static/test/integration/testability_spec.ts @@ -13,9 +13,9 @@ import { NgZone, provideZoneChangeDetection, } from '@angular/core'; -import {fakeAsync, flush, tick} from '@angular/core/testing'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; +import {timeout} from '@angular/private/testing'; import {UpgradeModule} from '../../../static'; import * as angular from '../../../src/common/src/angular1'; @@ -33,7 +33,7 @@ withEachNg1Version(() => { ngDoBootstrap() {} } - it('should handle deferred bootstrap', fakeAsync(() => { + it('should handle deferred bootstrap', async () => { let applicationRunning = false; let stayedInTheZone: boolean = undefined!; const ng1Module = angular.module_('ng1', []).run(() => { @@ -44,19 +44,19 @@ withEachNg1Version(() => { const element = html('
'); window.name = 'NG_DEFER_BOOTSTRAP!' + window.name; - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); setTimeout(() => { (window).angular.resumeBootstrap(); - }, 100); + }, 10); expect(applicationRunning).toEqual(false); - tick(100); + await timeout(10); expect(applicationRunning).toEqual(true); expect(stayedInTheZone).toEqual(true); - })); + }); - it('should propagate return value of resumeBootstrap', fakeAsync(() => { + it('should propagate return value of resumeBootstrap', async () => { const ng1Module = angular.module_('ng1', []); let a1Injector: angular.IInjectorService | undefined; ng1Module.run([ @@ -68,85 +68,81 @@ withEachNg1Version(() => { const element = html('
'); window.name = 'NG_DEFER_BOOTSTRAP!' + window.name; - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); - - tick(100); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); const value = (window).angular.resumeBootstrap(); expect(value).toBe(a1Injector); - flush(); - })); + await timeout(); + }); - it('should wait for ng2 testability', fakeAsync(() => { + it('should wait for ng2 testability', async () => { const ng1Module = angular.module_('ng1', []); const element = html('
'); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - const zone = upgrade.injector.get(NgZone); - let ng2Stable = false; - let ng1Stable = false; + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const zone = upgrade.injector.get(NgZone); + let ng2Stable = false; + let ng1Stable = false; - zone.run(() => { - setTimeout(() => { - ng2Stable = true; - }, 100); - }); - - angular.getTestability(element).whenStable(() => { - ng1Stable = true; - }); - - expect(ng1Stable).toEqual(false); - expect(ng2Stable).toEqual(false); - tick(100); - expect(ng1Stable).toEqual(true); - expect(ng2Stable).toEqual(true); - }); - })); - - it('should not wait for $interval', fakeAsync(() => { - const ng1Module = angular.module_('ng1', []); - const element = html('
'); - - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - const ng2Testability: Testability = upgrade.injector.get(Testability); - const $interval: angular.IIntervalService = upgrade.$injector.get('$interval'); - - let ng2Stable = false; - let intervalDone = false; - - const id = $interval( - (arg: string) => { - // should only be called once - expect(intervalDone).toEqual(false); - - intervalDone = true; - expect(NgZone.isInAngularZone()).toEqual(true); - expect(arg).toEqual('passed argument'); - }, - 200, - 0, - true, - 'passed argument', - ); - - ng2Testability.whenStable(() => { + zone.run(() => { + setTimeout(() => { ng2Stable = true; - }); - - tick(100); - - expect(intervalDone).toEqual(false); - expect(ng2Stable).toEqual(true); - - tick(200); - expect(intervalDone).toEqual(true); - expect($interval.cancel(id)).toEqual(true); - - // Interval should not fire after cancel - tick(200); + }, 10); }); - })); + + angular.getTestability(element).whenStable(() => { + ng1Stable = true; + }); + + expect(ng1Stable).toEqual(false); + expect(ng2Stable).toEqual(false); + await timeout(10); + expect(ng1Stable).toEqual(true); + expect(ng2Stable).toEqual(true); + }); + + it('should not wait for $interval', async () => { + const ng1Module = angular.module_('ng1', []); + const element = html('
'); + + const upgrade = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const ng2Testability: Testability = upgrade.injector.get(Testability); + const $interval: angular.IIntervalService = upgrade.$injector.get('$interval'); + + let ng2Stable = false; + let intervalDone = false; + + const id = $interval( + (arg: string) => { + // should only be called once + expect(intervalDone).toEqual(false); + + intervalDone = true; + expect(NgZone.isInAngularZone()).toEqual(true); + expect(arg).toEqual('passed argument'); + }, + 20, + 0, + true, + 'passed argument', + ); + + ng2Testability.whenStable(() => { + ng2Stable = true; + }); + + await timeout(10); + + expect(intervalDone).toEqual(false); + expect(ng2Stable).toEqual(true); + + await timeout(20); + expect(intervalDone).toEqual(true); + expect($interval.cancel(id)).toEqual(true); + + // Interval should not fire after cancel + await timeout(20); + }); }); }); diff --git a/packages/upgrade/static/test/integration/upgrade_component_spec.ts b/packages/upgrade/static/test/integration/upgrade_component_spec.ts index 7ac136812c2..7dd654fef87 100644 --- a/packages/upgrade/static/test/integration/upgrade_component_spec.ts +++ b/packages/upgrade/static/test/integration/upgrade_component_spec.ts @@ -21,9 +21,9 @@ import { Output, SimpleChanges, } from '@angular/core'; -import {fakeAsync, tick, 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 * as angular from '../../../src/common/src/angular1'; import {$EXCEPTION_HANDLER, $SCOPE} from '../../../src/common/src/constants'; @@ -42,7 +42,7 @@ withEachNg1Version(() => { afterEach(() => destroyPlatform()); describe('template/templateUrl', () => { - it('should support `template` (string)', waitForAsync(() => { + it('should support `template` (string)', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = {template: 'Hello, Angular!'}; @@ -83,12 +83,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((upgrade) => { - expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); + }); - it('should support `template` (function)', waitForAsync(() => { + it('should support `template` (function)', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = {template: () => 'Hello, Angular!'}; @@ -130,12 +129,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); + }); - it('should pass $element to `template` function and not $attrs', waitForAsync(() => { + it('should pass $element to `template` function and not $attrs', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = { template: ($attrs: angular.IAttributes, $element: angular.IAugmentedJQuery) => { @@ -184,12 +182,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); + }); - it('should support `templateUrl` (string) fetched from `$templateCache`', waitForAsync(() => { + it('should support `templateUrl` (string) fetched from `$templateCache`', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = {templateUrl: 'ng1.component.html'}; @@ -234,12 +231,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); + }); - it('should support `templateUrl` (function) fetched from `$templateCache`', waitForAsync(() => { + it('should support `templateUrl` (function) fetched from `$templateCache`', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = {templateUrl: () => 'ng1.component.html'}; @@ -284,12 +280,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); + }); - it('should pass $element to `templateUrl` function and not $attrs', waitForAsync(() => { + it('should pass $element to `templateUrl` function and not $attrs', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = { templateUrl: ($attrs: angular.IAttributes, $element: angular.IAugmentedJQuery) => { @@ -341,13 +336,12 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Hello, Angular!'); + }); // NOT SUPPORTED YET - xit('should support `templateUrl` (string) fetched from the server', fakeAsync(() => { + xit('should support `templateUrl` (string) fetched from the server', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = {templateUrl: 'ng1.component.html'}; @@ -377,7 +371,7 @@ withEachNg1Version(() => { .component('ng1', ng1Component) .directive('ng2', downgradeComponent({component: Ng2Component})) .value('$httpBackend', (method: string, url: string, post: any, callback: Function) => - setTimeout(() => callback(200, `${method}:${url}`.toLowerCase()), 1000), + setTimeout(() => callback(200, `${method}:${url}`.toLowerCase()), 20), ); // Define `Ng2Module` @@ -392,17 +386,16 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - tick(500); - expect(multiTrim(element.textContent)).toBe(''); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + await timeout(5); + expect(multiTrim(element.textContent)).toBe(''); - tick(500); - expect(multiTrim(element.textContent)).toBe('get:ng1.component.html'); - }); - })); + await timeout(20); + expect(multiTrim(element.textContent)).toBe('get:ng1.component.html'); + }); // NOT SUPPORTED YET - xit('should support `templateUrl` (function) fetched from the server', fakeAsync(() => { + xit('should support `templateUrl` (function) fetched from the server', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = {templateUrl: () => 'ng1.component.html'}; @@ -432,7 +425,7 @@ withEachNg1Version(() => { .component('ng1', ng1Component) .directive('ng2', downgradeComponent({component: Ng2Component})) .value('$httpBackend', (method: string, url: string, post: any, callback: Function) => - setTimeout(() => callback(200, `${method}:${url}`.toLowerCase()), 1000), + setTimeout(() => callback(200, `${method}:${url}`.toLowerCase()), 20), ); // Define `Ng2Module` @@ -447,16 +440,15 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - tick(500); - expect(multiTrim(element.textContent)).toBe(''); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + await timeout(5); + expect(multiTrim(element.textContent)).toBe(''); - tick(500); - expect(multiTrim(element.textContent)).toBe('get:ng1.component.html'); - }); - })); + await timeout(20); + expect(multiTrim(element.textContent)).toBe('get:ng1.component.html'); + }); - it('should support empty templates', waitForAsync(() => { + it('should support empty templates', async () => { // Define `ng1Component`s const ng1ComponentA: angular.IComponent = {template: ''}; const ng1ComponentB: angular.IComponent = {template: () => ''}; @@ -546,14 +538,13 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe(''); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe(''); + }); }); describe('bindings', () => { - it('should support `@` bindings', fakeAsync(() => { + it('should support `@` bindings', async () => { let ng2ComponentInstance: Ng2Component; // Define `ng1Component` @@ -613,28 +604,27 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - const ng1 = element.querySelector('ng1')!; - const ng1Controller = angular.element(ng1).controller?.('ng1'); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const ng1 = element.querySelector('ng1')!; + const ng1Controller = angular.element(ng1).controller?.('ng1'); - expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar'); + expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar'); - ng1Controller.inputA = 'baz'; - ng1Controller.inputB = 'qux'; - tick(); + ng1Controller.inputA = 'baz'; + ng1Controller.inputB = 'qux'; + await timeout(); - expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: foo, bar'); + expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: foo, bar'); - ng2ComponentInstance.dataA = 'foo2'; - ng2ComponentInstance.dataB = 'bar2'; - $digest(adapter); - tick(); + ng2ComponentInstance!.dataA = 'foo2'; + ng2ComponentInstance!.dataB = 'bar2'; + $digest(adapter); + await timeout(); - expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2'); - }); - })); + expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2'); + }); - it('should support `<` bindings', fakeAsync(() => { + it('should support `<` bindings', async () => { let ng2ComponentInstance: Ng2Component; // Define `ng1Component` @@ -694,28 +684,27 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - const ng1 = element.querySelector('ng1')!; - const ng1Controller = angular.element(ng1).controller?.('ng1'); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const ng1 = element.querySelector('ng1')!; + const ng1Controller = angular.element(ng1).controller?.('ng1'); - expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar'); + expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar'); - ng1Controller.inputA = {value: 'baz'}; - ng1Controller.inputB = {value: 'qux'}; - tick(); + ng1Controller.inputA = {value: 'baz'}; + ng1Controller.inputB = {value: 'qux'}; + await timeout(); - expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: foo, bar'); + expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: foo, bar'); - ng2ComponentInstance.dataA = {value: 'foo2'}; - ng2ComponentInstance.dataB = {value: 'bar2'}; - $digest(adapter); - tick(); + ng2ComponentInstance!.dataA = {value: 'foo2'}; + ng2ComponentInstance!.dataB = {value: 'bar2'}; + $digest(adapter); + await timeout(); - expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2'); - }); - })); + expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2'); + }); - it('should support `=` bindings', fakeAsync(() => { + it('should support `=` bindings', async () => { let ng2ComponentInstance: Ng2Component; // Define `ng1Component` @@ -777,28 +766,27 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - const ng1 = element.querySelector('ng1')!; - const ng1Controller = angular.element(ng1).controller?.('ng1'); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const ng1 = element.querySelector('ng1')!; + const ng1Controller = angular.element(ng1).controller?.('ng1'); - expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar'); + expect(multiTrim(element.textContent)).toBe('Inside: foo, bar | Outside: foo, bar'); - ng1Controller.inputA = {value: 'baz'}; - ng1Controller.inputB = {value: 'qux'}; - tick(); + ng1Controller.inputA = {value: 'baz'}; + ng1Controller.inputB = {value: 'qux'}; + await timeout(); - expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: baz, qux'); + expect(multiTrim(element.textContent)).toBe('Inside: baz, qux | Outside: baz, qux'); - ng2ComponentInstance.dataA = {value: 'foo2'}; - ng2ComponentInstance.dataB = {value: 'bar2'}; - $digest(adapter); - tick(); + ng2ComponentInstance!.dataA = {value: 'foo2'}; + ng2ComponentInstance!.dataB = {value: 'bar2'}; + $digest(adapter); + await timeout(); - expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2'); - }); - })); + expect(multiTrim(element.textContent)).toBe('Inside: foo2, bar2 | Outside: foo2, bar2'); + }); - it('should support `&` bindings', fakeAsync(() => { + it('should support `&` bindings', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = { template: 'Inside: -', @@ -852,21 +840,20 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - const ng1 = element.querySelector('ng1')!; - const ng1Controller = angular.element(ng1).controller?.('ng1'); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const ng1 = element.querySelector('ng1')!; + const ng1Controller = angular.element(ng1).controller?.('ng1'); - expect(multiTrim(element.textContent)).toBe('Inside: - | Outside: foo, bar'); + expect(multiTrim(element.textContent)).toBe('Inside: - | Outside: foo, bar'); - ng1Controller.outputA('baz'); - ng1Controller.outputB('qux'); - tick(); + ng1Controller.outputA('baz'); + ng1Controller.outputB('qux'); + await timeout(); - expect(multiTrim(element.textContent)).toBe('Inside: - | Outside: baz, qux'); - }); - })); + expect(multiTrim(element.textContent)).toBe('Inside: - | Outside: baz, qux'); + }); - it('should bind properties, events', fakeAsync(() => { + it('should bind properties, events', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = { template: ` @@ -954,25 +941,24 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe( - 'Hello Savkin, Victor, SF; A: VICTOR; B: SAVKIN; C: sf | ' + - 'Hello TEST; A: First; B: Last; C: City | ' + - 'WORKS - SAVKIN, Victor, SF', - ); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe( + 'Hello Savkin, Victor, SF; A: VICTOR; B: SAVKIN; C: sf | ' + + 'Hello TEST; A: First; B: Last; C: City | ' + + 'WORKS - SAVKIN, Victor, SF', + ); - // Detect changes - tick(); + // Detect changes + await timeout(); - expect(multiTrim(element.textContent)).toBe( - 'Hello SAVKIN, Victor, SF; A: VICTOR; B: SAVKIN; C: sf | ' + - 'Hello TEST; A: First; B: Last; C: City | ' + - 'WORKS - SAVKIN, Victor, SF', - ); - }); - })); + expect(multiTrim(element.textContent)).toBe( + 'Hello SAVKIN, Victor, SF; A: VICTOR; B: SAVKIN; C: sf | ' + + 'Hello TEST; A: First; B: Last; C: City | ' + + 'WORKS - SAVKIN, Victor, SF', + ); + }); - it('should bind optional properties', fakeAsync(() => { + it('should bind optional properties', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = { template: 'Inside: {{ $ctrl.inputA.value }}, {{ $ctrl.inputB }}', @@ -1036,39 +1022,38 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - const ng1s = element.querySelectorAll('ng1')!; - const ng1Controller0 = angular.element(ng1s[0]).controller?.('ng1'); - const ng1Controller1 = angular.element(ng1s[1]).controller?.('ng1'); - const ng1Controller2 = angular.element(ng1s[2]).controller?.('ng1'); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const ng1s = element.querySelectorAll('ng1')!; + const ng1Controller0 = angular.element(ng1s[0]).controller?.('ng1'); + const ng1Controller1 = angular.element(ng1s[1]).controller?.('ng1'); + const ng1Controller2 = angular.element(ng1s[2]).controller?.('ng1'); - expect(multiTrim(element.textContent)).toBe( - 'Inside: foo, bar | Inside: , Bar | Inside: , | Inside: , | Outside: foo, bar', - ); + expect(multiTrim(element.textContent)).toBe( + 'Inside: foo, bar | Inside: , Bar | Inside: , | Inside: , | Outside: foo, bar', + ); - ng1Controller0.inputA.value = 'baz'; - ng1Controller0.inputB = 'qux'; - tick(); + ng1Controller0.inputA.value = 'baz'; + ng1Controller0.inputB = 'qux'; + await timeout(); - expect(multiTrim(element.textContent)).toBe( - 'Inside: baz, qux | Inside: , Bar | Inside: , | Inside: , | Outside: baz, qux', - ); + expect(multiTrim(element.textContent)).toBe( + 'Inside: baz, qux | Inside: , Bar | Inside: , | Inside: , | Outside: baz, qux', + ); - ng1Controller1.outputA({value: 'foo again'}); - ng1Controller2.outputB('bar again'); - $digest(adapter); - tick(); + ng1Controller1.outputA({value: 'foo again'}); + ng1Controller2.outputB('bar again'); + $digest(adapter); + await timeout(); - expect(ng1Controller0.inputA).toEqual({value: 'foo again'}); - expect(ng1Controller0.inputB).toEqual('bar again'); - expect(multiTrim(element.textContent)).toBe( - 'Inside: foo again, bar again | Inside: , Bar | Inside: , | Inside: , | ' + - 'Outside: foo again, bar again', - ); - }); - })); + expect(ng1Controller0.inputA).toEqual({value: 'foo again'}); + expect(ng1Controller0.inputB).toEqual('bar again'); + expect(multiTrim(element.textContent)).toBe( + 'Inside: foo again, bar again | Inside: , Bar | Inside: , | Inside: , | ' + + 'Outside: foo again, bar again', + ); + }); - it('should bind properties, events to scope when bindToController is not used', fakeAsync(() => { + it('should bind properties, events to scope when bindToController is not used', async () => { // Define `ng1Directive` const ng1Directive: angular.IDirective = { template: '{{ someText }} - Data: {{ inputA }} - Length: {{ inputA.length }}', @@ -1127,35 +1112,34 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - const ng1 = element.querySelector('[ng1]')!; - const ng1Controller = angular.element(ng1).controller?.('ng1'); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const ng1 = element.querySelector('[ng1]')!; + const ng1Controller = angular.element(ng1).controller?.('ng1'); - expect(multiTrim(element.textContent)).toBe( - 'ng1 - Data: [1,2,3] - Length: 3 | ng2 - Data: 1,2,3 - Length: 3', - ); + expect(multiTrim(element.textContent)).toBe( + 'ng1 - Data: [1,2,3] - Length: 3 | ng2 - Data: 1,2,3 - Length: 3', + ); - ng1Controller.$scope.inputA = [4, 5]; - tick(); + ng1Controller.$scope.inputA = [4, 5]; + await timeout(); - expect(multiTrim(element.textContent)).toBe( - 'ng1 - Data: [4,5] - Length: 2 | ng2 - Data: 4,5 - Length: 2', - ); + expect(multiTrim(element.textContent)).toBe( + 'ng1 - Data: [4,5] - Length: 2 | ng2 - Data: 4,5 - Length: 2', + ); - ng1Controller.$scope.outputA(6); - $digest(adapter); - tick(); + ng1Controller.$scope.outputA(6); + $digest(adapter); + await timeout(); - expect(ng1Controller.$scope.inputA).toEqual([4, 5, 6]); - expect(multiTrim(element.textContent)).toBe( - 'ng1 - Data: [4,5,6] - Length: 3 | ng2 - Data: 4,5,6 - Length: 3', - ); - }); - })); + expect(ng1Controller.$scope.inputA).toEqual([4, 5, 6]); + expect(multiTrim(element.textContent)).toBe( + 'ng1 - Data: [4,5,6] - Length: 3 | ng2 - Data: 4,5,6 - Length: 3', + ); + }); }); describe('compiling', () => { - it('should compile the ng1 template in the correct DOM context', waitForAsync(() => { + it('should compile the ng1 template in the correct DOM context', async () => { let grandParentNodeName: string; // Define `ng1Component` @@ -1206,14 +1190,13 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(grandParentNodeName).toBe('NG2-X'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(grandParentNodeName!).toBe('NG2-X'); + }); }); describe('linking', () => { - it('should run the pre-linking after instantiating the controller', waitForAsync(() => { + it('should run the pre-linking after instantiating the controller', async () => { const log: string[] = []; // Define `ng1Directive` @@ -1265,12 +1248,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(log).toEqual(['ng1-ctrl', 'ng1-pre']); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(log).toEqual(['ng1-ctrl', 'ng1-pre']); + }); - it('should run the pre-linking function before linking', waitForAsync(() => { + it('should run the pre-linking function before linking', async () => { const log: string[] = []; // Define `ng1Directive` @@ -1320,12 +1302,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(log).toEqual(['ng1A-pre', 'ng1B-post']); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(log).toEqual(['ng1A-pre', 'ng1B-post']); + }); - it('should run the post-linking function after linking (link: object)', waitForAsync(() => { + it('should run the post-linking function after linking (link: object)', async () => { const log: string[] = []; // Define `ng1Directive` @@ -1375,12 +1356,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(log).toEqual(['ng1B-post', 'ng1A-post']); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(log).toEqual(['ng1B-post', 'ng1A-post']); + }); - it('should run the post-linking function after linking (link: function)', waitForAsync(() => { + it('should run the post-linking function after linking (link: function)', async () => { const log: string[] = []; // Define `ng1Directive` @@ -1430,12 +1410,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(log).toEqual(['ng1B-post', 'ng1A-post']); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(log).toEqual(['ng1B-post', 'ng1A-post']); + }); - it('should run the post-linking function before `$postLink`', waitForAsync(() => { + it('should run the post-linking function before `$postLink`', async () => { const log: string[] = []; // Define `ng1Directive` @@ -1487,14 +1466,13 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(log).toEqual(['ng1-post', 'ng1-$post']); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(log).toEqual(['ng1-post', 'ng1-$post']); + }); }); describe('controller', () => { - it('should support `controllerAs`', waitForAsync(() => { + it('should support `controllerAs`', async () => { // Define `ng1Directive` const ng1Directive: angular.IDirective = { template: '{{ vm.scope }}; {{ vm.isClass }}; {{ vm.hasElement }}; {{ vm.isPublished() }}', @@ -1563,12 +1541,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('scope; isClass; NG1; published'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('scope; isClass; NG1; published'); + }); - it('should support `bindToController` (boolean)', waitForAsync(() => { + it('should support `bindToController` (boolean)', async () => { // Define `ng1Directive` const ng1DirectiveA: angular.IDirective = { template: 'Scope: {{ title }}; Controller: {{ $ctrl.title }}', @@ -1643,14 +1620,13 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe( - 'Scope: WORKS; Controller: | Scope: ; Controller: WORKS', - ); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe( + 'Scope: WORKS; Controller: | Scope: ; Controller: WORKS', + ); + }); - it('should support `bindToController` (object)', waitForAsync(() => { + it('should support `bindToController` (object)', async () => { // Define `ng1Directive` const ng1Directive: angular.IDirective = { template: '{{ $ctrl.title }}', @@ -1703,12 +1679,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('WORKS'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('WORKS'); + }); - it('should support `controller` as string', waitForAsync(() => { + it('should support `controller` as string', async () => { // Define `ng1Directive` const ng1Directive: angular.IDirective = { template: '{{ $ctrl.title }} {{ $ctrl.text }}', @@ -1763,12 +1738,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('WORKS GREAT'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('WORKS GREAT'); + }); - it('should insert the compiled content before instantiating the controller', waitForAsync(() => { + it('should insert the compiled content before instantiating the controller', async () => { let compiledContent: string; let getCurrentContent: () => string; @@ -1823,17 +1797,16 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(compiledContent)).toBe('Hello, {{ $ctrl.name }}!'); - expect(multiTrim(getCurrentContent())).toBe('Hello, world!'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(compiledContent!)).toBe('Hello, {{ $ctrl.name }}!'); + expect(multiTrim(getCurrentContent!())).toBe('Hello, world!'); + }); }); describe('require', () => { // NOT YET SUPPORTED xdescribe('in pre-/post-link', () => { - it('should resolve to its own controller if falsy', waitForAsync(() => { + it('should resolve to its own controller if falsy', async () => { // Define `ng1Directive` const ng1Directive: angular.IDirective = { template: 'Pre: {{ pre }} | Post: {{ post }}', @@ -1888,16 +1861,15 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(document.body.textContent)).toBe('Pre: foo | Post: foo'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toBe('Pre: foo | Post: foo'); + }); // TODO: Add more tests }); describe('in controller', () => { - it('should be available to children', waitForAsync(() => { + it('should be available to children', async () => { // Define `ng1Component` const ng1ComponentA: angular.IComponent = { template: '', @@ -1950,12 +1922,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Required: ng1A'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Required: ng1A'); + }); - it('should throw if required controller cannot be found', waitForAsync(() => { + it('should throw if required controller cannot be found', async () => { // Define `ng1Component` const ng1ComponentA: angular.IComponent = {require: {foo: 'iDoNotExist'}}; const ng1ComponentB: angular.IComponent = {require: {foo: '^iDoNotExist'}}; @@ -2050,26 +2021,23 @@ withEachNg1Version(() => { const elementB = html(``); const elementC = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, elementA, ng1Module).then(() => { - expect(mockExceptionHandler).toHaveBeenCalledWith( - new Error("Unable to find required 'iDoNotExist' in upgraded directive 'ng1A'."), - ); - }); + await bootstrap(platformBrowserDynamic(), Ng2Module, elementA, ng1Module); + expect(mockExceptionHandler).toHaveBeenCalledWith( + new Error("Unable to find required 'iDoNotExist' in upgraded directive 'ng1A'."), + ); - bootstrap(platformBrowserDynamic(), Ng2Module, elementB, ng1Module).then(() => { - expect(mockExceptionHandler).toHaveBeenCalledWith( - new Error("Unable to find required '^iDoNotExist' in upgraded directive 'ng1B'."), - ); - }); + await bootstrap(platformBrowserDynamic(), Ng2Module, elementB, ng1Module); + expect(mockExceptionHandler).toHaveBeenCalledWith( + new Error("Unable to find required '^iDoNotExist' in upgraded directive 'ng1B'."), + ); - bootstrap(platformBrowserDynamic(), Ng2Module, elementC, ng1Module).then(() => { - expect(mockExceptionHandler).toHaveBeenCalledWith( - new Error("Unable to find required '^^iDoNotExist' in upgraded directive 'ng1C'."), - ); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, elementC, ng1Module); + expect(mockExceptionHandler).toHaveBeenCalledWith( + new Error("Unable to find required '^^iDoNotExist' in upgraded directive 'ng1C'."), + ); + }); - it('should not throw if missing required controller is optional', waitForAsync(() => { + it('should not throw if missing required controller is optional', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = { require: { @@ -2119,12 +2087,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(mockExceptionHandler).not.toHaveBeenCalled(); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(mockExceptionHandler).not.toHaveBeenCalled(); + }); - it('should assign resolved values to the controller instance (if `require` is not object)', waitForAsync(() => { + it('should assign resolved values to the controller instance (if `require` is not object)', async () => { // Define `ng1Component` const ng1ComponentA: angular.IComponent = { template: 'ng1A(
)', @@ -2205,12 +2172,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('ng1A(ng2(ng1B() | ng1C()))'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('ng1A(ng2(ng1B() | ng1C()))'); + }); - it('should assign resolved values to the controller instance (if `require` is object)', waitForAsync(() => { + it('should assign resolved values to the controller instance (if `require` is object)', async () => { // Define `ng1Component` const ng1ComponentA: angular.IComponent = { template: 'ng1A(
)', @@ -2280,14 +2246,13 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe( - 'ng1A(ng2(ng1B( ng1A: | ^ng1A: A | ^^ng1A: A | ng1B: B | ^ng1B: B | ^^ng1B: )))', - ); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe( + 'ng1A(ng2(ng1B( ng1A: | ^ng1A: A | ^^ng1A: A | ng1B: B | ^ng1B: B | ^^ng1B: )))', + ); + }); - it('should assign to controller before calling `$onInit()`', waitForAsync(() => { + it('should assign to controller before calling `$onInit()`', async () => { // Define `ng1Component` const ng1ComponentA: angular.IComponent = { template: '', @@ -2346,12 +2311,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('$onInit: ng1A'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('$onInit: ng1A'); + }); - it('should use the key as name if the required controller name is omitted', waitForAsync(() => { + it('should use the key as name if the required controller name is omitted', async () => { // Define `ng1Component` const ng1ComponentA: angular.IComponent = { template: '', @@ -2420,15 +2384,14 @@ withEachNg1Version(() => { // Bootstrap const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('ng1A: A | ng1B: B | ng1C: C'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('ng1A: A | ng1B: B | ng1C: C'); + }); }); }); describe('transclusion', () => { - it('should support single-slot transclusion', waitForAsync(() => { + it('should support single-slot transclusion', async () => { let ng2ComponentAInstance: Ng2ComponentA; let ng2ComponentBInstance: Ng2ComponentB; @@ -2495,23 +2458,22 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(multiTrim(element.textContent)).toBe('ng2A(ng1(foo | ))'); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('ng2A(ng1(foo | ))'); - ng2ComponentAInstance.value = 'baz'; - ng2ComponentAInstance.showB = true; - $digest(adapter); + ng2ComponentAInstance!.value = 'baz'; + ng2ComponentAInstance!.showB = true; + $digest(adapter); - expect(multiTrim(element.textContent)).toBe('ng2A(ng1(baz | ng2B(bar)))'); + expect(multiTrim(element.textContent)).toBe('ng2A(ng1(baz | ng2B(bar)))'); - ng2ComponentBInstance.value = 'qux'; - $digest(adapter); + ng2ComponentBInstance!.value = 'qux'; + $digest(adapter); - expect(multiTrim(element.textContent)).toBe('ng2A(ng1(baz | ng2B(qux)))'); - }); - })); + expect(multiTrim(element.textContent)).toBe('ng2A(ng1(baz | ng2B(qux)))'); + }); - it('should support single-slot transclusion with fallback content', waitForAsync(() => { + it('should support single-slot transclusion with fallback content', async () => { let ng1ControllerInstances: any[] = []; let ng2ComponentInstance: Ng2Component; @@ -2570,18 +2532,17 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(multiTrim(element.textContent)).toBe('ng2(ng1(from-ng2) | ng1(from-ng1))'); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('ng2(ng1(from-ng2) | ng1(from-ng1))'); - ng1ControllerInstances.forEach((ctrl) => (ctrl.value = 'ng1-foo')); - ng2ComponentInstance.value = 'ng2-bar'; - $digest(adapter); + ng1ControllerInstances.forEach((ctrl) => (ctrl.value = 'ng1-foo')); + ng2ComponentInstance!.value = 'ng2-bar'; + $digest(adapter); - expect(multiTrim(element.textContent)).toBe('ng2(ng1(ng2-bar) | ng1(ng1-foo))'); - }); - })); + expect(multiTrim(element.textContent)).toBe('ng2(ng1(ng2-bar) | ng1(ng1-foo))'); + }); - it('should support multi-slot transclusion', waitForAsync(() => { + it('should support multi-slot transclusion', async () => { let ng2ComponentInstance: Ng2Component; // Define `ng1Component` @@ -2643,18 +2604,17 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(foo1foo2)|y(bar1bar2)))'); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(foo1foo2)|y(bar1bar2)))'); - ng2ComponentInstance.x = 'baz'; - ng2ComponentInstance.y = 'qux'; - $digest(adapter); + ng2ComponentInstance!.x = 'baz'; + ng2ComponentInstance!.y = 'qux'; + $digest(adapter); - expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz1baz2)|y(qux1qux2)))'); - }); - })); + expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz1baz2)|y(qux1qux2)))'); + }); - it('should support default slot (with fallback content)', waitForAsync(() => { + it('should support default slot (with fallback content)', async () => { let ng1ControllerInstances: any[] = []; let ng2ComponentInstance: Ng2Component; @@ -2729,23 +2689,22 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(multiTrim(element.textContent, true)).toBe( - 'ng2(ng1(default((foo)foo-bar(bar)))|ng1(default(fallback-ng1)))', - ); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent, true)).toBe( + 'ng2(ng1(default((foo)foo-bar(bar)))|ng1(default(fallback-ng1)))', + ); - ng1ControllerInstances.forEach((ctrl) => (ctrl.value = 'ng1-plus')); - ng2ComponentInstance.x = 'baz'; - ng2ComponentInstance.y = 'qux'; - $digest(adapter); + ng1ControllerInstances.forEach((ctrl) => (ctrl.value = 'ng1-plus')); + ng2ComponentInstance!.x = 'baz'; + ng2ComponentInstance!.y = 'qux'; + $digest(adapter); - expect(multiTrim(element.textContent, true)).toBe( - 'ng2(ng1(default((baz)baz-qux(qux)))|ng1(default(fallback-ng1-plus)))', - ); - }); - })); + expect(multiTrim(element.textContent, true)).toBe( + 'ng2(ng1(default((baz)baz-qux(qux)))|ng1(default(fallback-ng1-plus)))', + ); + }); - it('should support optional transclusion slots (with fallback content)', waitForAsync(() => { + it('should support optional transclusion slots (with fallback content)', async () => { let ng1ControllerInstances: any[] = []; let ng2ComponentInstance: Ng2Component; @@ -2819,26 +2778,25 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(multiTrim(element.textContent, true)).toBe( - 'ng2(ng1(x(ng2X)|y(ng1Y))|ng1(x(ng1X)|y(ng2Y)))', - ); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent, true)).toBe( + 'ng2(ng1(x(ng2X)|y(ng1Y))|ng1(x(ng1X)|y(ng2Y)))', + ); - ng1ControllerInstances.forEach((ctrl) => { - ctrl.x = 'ng1X-foo'; - ctrl.y = 'ng1Y-bar'; - }); - ng2ComponentInstance.x = 'ng2X-baz'; - ng2ComponentInstance.y = 'ng2Y-qux'; - $digest(adapter); - - expect(multiTrim(element.textContent, true)).toBe( - 'ng2(ng1(x(ng2X-baz)|y(ng1Y-bar))|ng1(x(ng1X-foo)|y(ng2Y-qux)))', - ); + ng1ControllerInstances.forEach((ctrl) => { + ctrl.x = 'ng1X-foo'; + ctrl.y = 'ng1Y-bar'; }); - })); + ng2ComponentInstance!.x = 'ng2X-baz'; + ng2ComponentInstance!.y = 'ng2Y-qux'; + $digest(adapter); - it('should throw if a non-optional slot is not filled', waitForAsync(() => { + expect(multiTrim(element.textContent, true)).toBe( + 'ng2(ng1(x(ng2X-baz)|y(ng1Y-bar))|ng1(x(ng1X-foo)|y(ng2Y-qux)))', + ); + }); + + it('should throw if a non-optional slot is not filled', async () => { let errorMessage: string; // Define `ng1Component` @@ -2886,12 +2844,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(errorMessage).toContain("Required transclusion slot 'slotY' on directive: ng1"); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(errorMessage!).toContain("Required transclusion slot 'slotY' on directive: ng1"); + }); - it('should support structural directives in transcluded content', waitForAsync(() => { + it('should support structural directives in transcluded content', async () => { let ng2ComponentInstance: Ng2Component; // Define `ng1Component` @@ -2958,26 +2915,25 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(foo1)|default(bar2)))'); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(foo1)|default(bar2)))'); - ng2ComponentInstance.x = 'baz'; - ng2ComponentInstance.y = 'qux'; - ng2ComponentInstance.show = false; - $digest(adapter); + ng2ComponentInstance!.x = 'baz'; + ng2ComponentInstance!.y = 'qux'; + ng2ComponentInstance!.show = false; + $digest(adapter); - expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz2)|default(qux1)))'); + expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz2)|default(qux1)))'); - ng2ComponentInstance.show = true; - $digest(adapter); + ng2ComponentInstance!.show = true; + $digest(adapter); - expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz1)|default(qux2)))'); - }); - })); + expect(multiTrim(element.textContent, true)).toBe('ng2(ng1(x(baz1)|default(qux2)))'); + }); }); describe('lifecycle hooks', () => { - it('should call `$onChanges()` on binding destination (prototype)', fakeAsync(() => { + it('should call `$onChanges()` on binding destination (prototype)', async () => { const scopeOnChanges = jasmine.createSpy('scopeOnChanges'); const controllerOnChangesA = jasmine.createSpy('controllerOnChangesA'); const controllerOnChangesB = jasmine.createSpy('controllerOnChangesB'); @@ -3070,74 +3026,73 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - // Initial change - expect(scopeOnChanges.calls.count()).toBe(1); - expect(controllerOnChangesA).not.toHaveBeenCalled(); - expect(controllerOnChangesB.calls.count()).toBe(1); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + // Initial change + expect(scopeOnChanges.calls.count()).toBe(1); + expect(controllerOnChangesA).not.toHaveBeenCalled(); + expect(controllerOnChangesB.calls.count()).toBe(1); - expect(scopeOnChanges.calls.argsFor(0)[0]).toEqual({inputA: jasmine.any(Object)}); - expect(scopeOnChanges.calls.argsFor(0)[0].inputA.currentValue).toEqual({foo: 'bar'}); - expect(scopeOnChanges.calls.argsFor(0)[0].inputA.isFirstChange()).toBe(true); - expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.currentValue).toEqual({ - foo: 'bar', - }); - expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.isFirstChange()).toBe(true); - - // Change: Re-assign `data` - ng2ComponentInstance.data = {foo: 'baz'}; - $digest(adapter); - tick(); - - expect(scopeOnChanges.calls.count()).toBe(2); - expect(controllerOnChangesA).not.toHaveBeenCalled(); - expect(controllerOnChangesB.calls.count()).toBe(2); - - expect(scopeOnChanges.calls.argsFor(1)[0]).toEqual({inputA: jasmine.any(Object)}); - expect(scopeOnChanges.calls.argsFor(1)[0].inputA.previousValue).toEqual({foo: 'bar'}); - expect(scopeOnChanges.calls.argsFor(1)[0].inputA.currentValue).toEqual({foo: 'baz'}); - expect(scopeOnChanges.calls.argsFor(1)[0].inputA.isFirstChange()).toBe(false); - expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.previousValue).toEqual({ - foo: 'bar', - }); - expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.currentValue).toEqual({ - foo: 'baz', - }); - expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.isFirstChange()).toBe(false); - - // No change: Update internal property - ng2ComponentInstance.data.foo = 'qux'; - $digest(adapter); - tick(); - - expect(scopeOnChanges.calls.count()).toBe(2); - expect(controllerOnChangesA).not.toHaveBeenCalled(); - expect(controllerOnChangesB.calls.count()).toBe(2); - - // Change: Re-assign `data` (even if it looks the same) - ng2ComponentInstance.data = {foo: 'qux'}; - $digest(adapter); - tick(); - - expect(scopeOnChanges.calls.count()).toBe(3); - expect(controllerOnChangesA).not.toHaveBeenCalled(); - expect(controllerOnChangesB.calls.count()).toBe(3); - - expect(scopeOnChanges.calls.argsFor(2)[0]).toEqual({inputA: jasmine.any(Object)}); - expect(scopeOnChanges.calls.argsFor(2)[0].inputA.previousValue).toEqual({foo: 'qux'}); - expect(scopeOnChanges.calls.argsFor(2)[0].inputA.currentValue).toEqual({foo: 'qux'}); - expect(scopeOnChanges.calls.argsFor(2)[0].inputA.isFirstChange()).toBe(false); - expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.previousValue).toEqual({ - foo: 'qux', - }); - expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.currentValue).toEqual({ - foo: 'qux', - }); - expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.isFirstChange()).toBe(false); + expect(scopeOnChanges.calls.argsFor(0)[0]).toEqual({inputA: jasmine.any(Object)}); + expect(scopeOnChanges.calls.argsFor(0)[0].inputA.currentValue).toEqual({foo: 'bar'}); + expect(scopeOnChanges.calls.argsFor(0)[0].inputA.isFirstChange()).toBe(true); + expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.currentValue).toEqual({ + foo: 'bar', }); - })); + expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.isFirstChange()).toBe(true); - it('should call `$onChanges()` on binding destination (instance)', fakeAsync(() => { + // Change: Re-assign `data` + ng2ComponentInstance!.data = {foo: 'baz'}; + $digest(adapter); + await timeout(); + + expect(scopeOnChanges.calls.count()).toBe(2); + expect(controllerOnChangesA).not.toHaveBeenCalled(); + expect(controllerOnChangesB.calls.count()).toBe(2); + + expect(scopeOnChanges.calls.argsFor(1)[0]).toEqual({inputA: jasmine.any(Object)}); + expect(scopeOnChanges.calls.argsFor(1)[0].inputA.previousValue).toEqual({foo: 'bar'}); + expect(scopeOnChanges.calls.argsFor(1)[0].inputA.currentValue).toEqual({foo: 'baz'}); + expect(scopeOnChanges.calls.argsFor(1)[0].inputA.isFirstChange()).toBe(false); + expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.previousValue).toEqual({ + foo: 'bar', + }); + expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.currentValue).toEqual({ + foo: 'baz', + }); + expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.isFirstChange()).toBe(false); + + // No change: Update internal property + ng2ComponentInstance!.data.foo = 'qux'; + $digest(adapter); + await timeout(); + + expect(scopeOnChanges.calls.count()).toBe(2); + expect(controllerOnChangesA).not.toHaveBeenCalled(); + expect(controllerOnChangesB.calls.count()).toBe(2); + + // Change: Re-assign `data` (even if it looks the same) + ng2ComponentInstance!.data = {foo: 'qux'}; + $digest(adapter); + await timeout(); + + expect(scopeOnChanges.calls.count()).toBe(3); + expect(controllerOnChangesA).not.toHaveBeenCalled(); + expect(controllerOnChangesB.calls.count()).toBe(3); + + expect(scopeOnChanges.calls.argsFor(2)[0]).toEqual({inputA: jasmine.any(Object)}); + expect(scopeOnChanges.calls.argsFor(2)[0].inputA.previousValue).toEqual({foo: 'qux'}); + expect(scopeOnChanges.calls.argsFor(2)[0].inputA.currentValue).toEqual({foo: 'qux'}); + expect(scopeOnChanges.calls.argsFor(2)[0].inputA.isFirstChange()).toBe(false); + expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.previousValue).toEqual({ + foo: 'qux', + }); + expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.currentValue).toEqual({ + foo: 'qux', + }); + expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.isFirstChange()).toBe(false); + }); + + it('should call `$onChanges()` on binding destination (instance)', async () => { const scopeOnChangesA = jasmine.createSpy('scopeOnChangesA'); const scopeOnChangesB = jasmine.createSpy('scopeOnChangesB'); const controllerOnChangesA = jasmine.createSpy('controllerOnChangesA'); @@ -3230,75 +3185,74 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - // Initial change - expect(scopeOnChangesA.calls.count()).toBe(1); - expect(scopeOnChangesB).not.toHaveBeenCalled(); - expect(controllerOnChangesA).not.toHaveBeenCalled(); - expect(controllerOnChangesB.calls.count()).toBe(1); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + // Initial change + expect(scopeOnChangesA.calls.count()).toBe(1); + expect(scopeOnChangesB).not.toHaveBeenCalled(); + expect(controllerOnChangesA).not.toHaveBeenCalled(); + expect(controllerOnChangesB.calls.count()).toBe(1); - expect(scopeOnChangesA.calls.argsFor(0)[0].inputA.currentValue).toEqual({foo: 'bar'}); - expect(scopeOnChangesA.calls.argsFor(0)[0].inputA.isFirstChange()).toBe(true); - expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.currentValue).toEqual({ - foo: 'bar', - }); - expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.isFirstChange()).toBe(true); - - // Change: Re-assign `data` - ng2ComponentInstance.data = {foo: 'baz'}; - $digest(adapter); - tick(); - - expect(scopeOnChangesA.calls.count()).toBe(2); - expect(scopeOnChangesB).not.toHaveBeenCalled(); - expect(controllerOnChangesA).not.toHaveBeenCalled(); - expect(controllerOnChangesB.calls.count()).toBe(2); - - expect(scopeOnChangesA.calls.argsFor(1)[0].inputA.previousValue).toEqual({foo: 'bar'}); - expect(scopeOnChangesA.calls.argsFor(1)[0].inputA.currentValue).toEqual({foo: 'baz'}); - expect(scopeOnChangesA.calls.argsFor(1)[0].inputA.isFirstChange()).toBe(false); - expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.previousValue).toEqual({ - foo: 'bar', - }); - expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.currentValue).toEqual({ - foo: 'baz', - }); - expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.isFirstChange()).toBe(false); - - // No change: Update internal property - ng2ComponentInstance.data.foo = 'qux'; - $digest(adapter); - tick(); - - expect(scopeOnChangesA.calls.count()).toBe(2); - expect(scopeOnChangesB).not.toHaveBeenCalled(); - expect(controllerOnChangesA).not.toHaveBeenCalled(); - expect(controllerOnChangesB.calls.count()).toBe(2); - - // Change: Re-assign `data` (even if it looks the same) - ng2ComponentInstance.data = {foo: 'qux'}; - $digest(adapter); - tick(); - - expect(scopeOnChangesA.calls.count()).toBe(3); - expect(scopeOnChangesB).not.toHaveBeenCalled(); - expect(controllerOnChangesA).not.toHaveBeenCalled(); - expect(controllerOnChangesB.calls.count()).toBe(3); - - expect(scopeOnChangesA.calls.argsFor(2)[0].inputA.previousValue).toEqual({foo: 'qux'}); - expect(scopeOnChangesA.calls.argsFor(2)[0].inputA.currentValue).toEqual({foo: 'qux'}); - expect(scopeOnChangesA.calls.argsFor(2)[0].inputA.isFirstChange()).toBe(false); - expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.previousValue).toEqual({ - foo: 'qux', - }); - expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.currentValue).toEqual({ - foo: 'qux', - }); - expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.isFirstChange()).toBe(false); + expect(scopeOnChangesA.calls.argsFor(0)[0].inputA.currentValue).toEqual({foo: 'bar'}); + expect(scopeOnChangesA.calls.argsFor(0)[0].inputA.isFirstChange()).toBe(true); + expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.currentValue).toEqual({ + foo: 'bar', }); - })); + expect(controllerOnChangesB.calls.argsFor(0)[0].inputB.isFirstChange()).toBe(true); - it('should call `$onInit()` on controller', waitForAsync(() => { + // Change: Re-assign `data` + ng2ComponentInstance!.data = {foo: 'baz'}; + $digest(adapter); + await timeout(); + + expect(scopeOnChangesA.calls.count()).toBe(2); + expect(scopeOnChangesB).not.toHaveBeenCalled(); + expect(controllerOnChangesA).not.toHaveBeenCalled(); + expect(controllerOnChangesB.calls.count()).toBe(2); + + expect(scopeOnChangesA.calls.argsFor(1)[0].inputA.previousValue).toEqual({foo: 'bar'}); + expect(scopeOnChangesA.calls.argsFor(1)[0].inputA.currentValue).toEqual({foo: 'baz'}); + expect(scopeOnChangesA.calls.argsFor(1)[0].inputA.isFirstChange()).toBe(false); + expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.previousValue).toEqual({ + foo: 'bar', + }); + expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.currentValue).toEqual({ + foo: 'baz', + }); + expect(controllerOnChangesB.calls.argsFor(1)[0].inputB.isFirstChange()).toBe(false); + + // No change: Update internal property + ng2ComponentInstance!.data.foo = 'qux'; + $digest(adapter); + await timeout(); + + expect(scopeOnChangesA.calls.count()).toBe(2); + expect(scopeOnChangesB).not.toHaveBeenCalled(); + expect(controllerOnChangesA).not.toHaveBeenCalled(); + expect(controllerOnChangesB.calls.count()).toBe(2); + + // Change: Re-assign `data` (even if it looks the same) + ng2ComponentInstance!.data = {foo: 'qux'}; + $digest(adapter); + await timeout(); + + expect(scopeOnChangesA.calls.count()).toBe(3); + expect(scopeOnChangesB).not.toHaveBeenCalled(); + expect(controllerOnChangesA).not.toHaveBeenCalled(); + expect(controllerOnChangesB.calls.count()).toBe(3); + + expect(scopeOnChangesA.calls.argsFor(2)[0].inputA.previousValue).toEqual({foo: 'qux'}); + expect(scopeOnChangesA.calls.argsFor(2)[0].inputA.currentValue).toEqual({foo: 'qux'}); + expect(scopeOnChangesA.calls.argsFor(2)[0].inputA.isFirstChange()).toBe(false); + expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.previousValue).toEqual({ + foo: 'qux', + }); + expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.currentValue).toEqual({ + foo: 'qux', + }); + expect(controllerOnChangesB.calls.argsFor(2)[0].inputB.isFirstChange()).toBe(false); + }); + + it('should call `$onInit()` on controller', async () => { // Define `ng1Directive` const ng1DirectiveA: angular.IDirective = { template: 'Called: {{ called }}', @@ -3374,12 +3328,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Called: yes | Called: yes'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Called: yes | Called: yes'); + }); - it('should not call `$onInit()` on scope', waitForAsync(() => { + it('should not call `$onInit()` on scope', async () => { // Define `ng1Directive` const ng1DirectiveA: angular.IDirective = { template: 'Called: {{ called }}', @@ -3454,12 +3407,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Called: no | Called: no'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Called: no | Called: no'); + }); - it('should call `$postLink()` on controller', waitForAsync(() => { + it('should call `$postLink()` on controller', async () => { // Define `ng1Directive` const ng1DirectiveA: angular.IDirective = { template: 'Called: {{ called }}', @@ -3535,12 +3487,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Called: yes | Called: yes'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Called: yes | Called: yes'); + }); - it('should not call `$postLink()` on scope', waitForAsync(() => { + it('should not call `$postLink()` on scope', async () => { // Define `ng1Directive` const ng1DirectiveA: angular.IDirective = { template: 'Called: {{ called }}', @@ -3615,12 +3566,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe('Called: no | Called: no'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('Called: no | Called: no'); + }); - it('should call `$doCheck()` on controller', waitForAsync(() => { + it('should call `$doCheck()` on controller', async () => { const controllerDoCheckA = jasmine.createSpy('controllerDoCheckA'); const controllerDoCheckB = jasmine.createSpy('controllerDoCheckB'); @@ -3694,30 +3644,29 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - // Get to a stable `$digest` state. - $digest(adapter); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + // Get to a stable `$digest` state. + $digest(adapter); - // Initial change. - // (Do not use a specific number due to differences between AngularJS 1.5/1.6.) - expect(controllerDoCheckA.calls.count()).toBeGreaterThan(0); - expect(controllerDoCheckB.calls.count()).toBeGreaterThan(0); - controllerDoCheckA.calls.reset(); - controllerDoCheckB.calls.reset(); + // Initial change. + // (Do not use a specific number due to differences between AngularJS 1.5/1.6.) + expect(controllerDoCheckA.calls.count()).toBeGreaterThan(0); + expect(controllerDoCheckB.calls.count()).toBeGreaterThan(0); + controllerDoCheckA.calls.reset(); + controllerDoCheckB.calls.reset(); - // Run a `$digest` - $digest(adapter); - expect(controllerDoCheckA.calls.count()).toBe(1); - expect(controllerDoCheckB.calls.count()).toBe(1); + // Run a `$digest` + $digest(adapter); + expect(controllerDoCheckA.calls.count()).toBe(1); + expect(controllerDoCheckB.calls.count()).toBe(1); - // Run another `$digest` - $digest(adapter); - expect(controllerDoCheckA.calls.count()).toBe(2); - expect(controllerDoCheckB.calls.count()).toBe(2); - }); - })); + // Run another `$digest` + $digest(adapter); + expect(controllerDoCheckA.calls.count()).toBe(2); + expect(controllerDoCheckB.calls.count()).toBe(2); + }); - it('should not call `$doCheck()` on scope', waitForAsync(() => { + it('should not call `$doCheck()` on scope', async () => { const scopeDoCheck = jasmine.createSpy('scopeDoCheck'); // Define `ng1Directive` @@ -3790,21 +3739,20 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - // Initial change - expect(scopeDoCheck).not.toHaveBeenCalled(); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + // Initial change + expect(scopeDoCheck).not.toHaveBeenCalled(); - // Run a `$digest` - $digest(adapter); - expect(scopeDoCheck).not.toHaveBeenCalled(); + // Run a `$digest` + $digest(adapter); + expect(scopeDoCheck).not.toHaveBeenCalled(); - // Run another `$digest` - $digest(adapter); - expect(scopeDoCheck).not.toHaveBeenCalled(); - }); - })); + // Run another `$digest` + $digest(adapter); + expect(scopeDoCheck).not.toHaveBeenCalled(); + }); - it('should call `$onDestroy()` on controller', waitForAsync(() => { + it('should call `$onDestroy()` on controller', async () => { const controllerOnDestroyA = jasmine.createSpy('controllerOnDestroyA'); const controllerOnDestroyB = jasmine.createSpy('controllerOnDestroyB'); @@ -3884,36 +3832,35 @@ withEachNg1Version(() => { // Bootstrap const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - const $rootScope = adapter.$injector.get('$rootScope') as angular.IRootScopeService; + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const $rootScope = adapter.$injector.get('$rootScope') as angular.IRootScopeService; - expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B'); - expect(controllerOnDestroyA).not.toHaveBeenCalled(); - expect(controllerOnDestroyB).not.toHaveBeenCalled(); + expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B'); + expect(controllerOnDestroyA).not.toHaveBeenCalled(); + expect(controllerOnDestroyB).not.toHaveBeenCalled(); - $rootScope.$apply('destroyFromNg1 = true'); + $rootScope.$apply('destroyFromNg1 = true'); - expect(multiTrim(document.body.textContent)).toBe(''); - expect(controllerOnDestroyA).toHaveBeenCalled(); - expect(controllerOnDestroyB).toHaveBeenCalled(); + expect(multiTrim(document.body.textContent)).toBe(''); + expect(controllerOnDestroyA).toHaveBeenCalled(); + expect(controllerOnDestroyB).toHaveBeenCalled(); - controllerOnDestroyA.calls.reset(); - controllerOnDestroyB.calls.reset(); - $rootScope.$apply('destroyFromNg1 = false'); + controllerOnDestroyA.calls.reset(); + controllerOnDestroyB.calls.reset(); + $rootScope.$apply('destroyFromNg1 = false'); - expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B'); - expect(controllerOnDestroyA).not.toHaveBeenCalled(); - expect(controllerOnDestroyB).not.toHaveBeenCalled(); + expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B'); + expect(controllerOnDestroyA).not.toHaveBeenCalled(); + expect(controllerOnDestroyB).not.toHaveBeenCalled(); - $rootScope.$apply('destroyFromNg2 = true'); + $rootScope.$apply('destroyFromNg2 = true'); - expect(multiTrim(document.body.textContent)).toBe(''); - expect(controllerOnDestroyA).toHaveBeenCalled(); - expect(controllerOnDestroyB).toHaveBeenCalled(); - }); - })); + expect(multiTrim(document.body.textContent)).toBe(''); + expect(controllerOnDestroyA).toHaveBeenCalled(); + expect(controllerOnDestroyB).toHaveBeenCalled(); + }); - it('should not call `$onDestroy()` on scope', waitForAsync(() => { + it('should not call `$onDestroy()` on scope', async () => { const scopeOnDestroy = jasmine.createSpy('scopeOnDestroy'); // Define `ng1Directive` @@ -3994,30 +3941,29 @@ withEachNg1Version(() => { // Bootstrap const element = html(''); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - const $rootScope = adapter.$injector.get('$rootScope') as angular.IRootScopeService; + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const $rootScope = adapter.$injector.get('$rootScope') as angular.IRootScopeService; - expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B'); - expect(scopeOnDestroy).not.toHaveBeenCalled(); + expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B'); + expect(scopeOnDestroy).not.toHaveBeenCalled(); - $rootScope.$apply('destroyFromNg1 = true'); + $rootScope.$apply('destroyFromNg1 = true'); - expect(multiTrim(document.body.textContent)).toBe(''); - expect(scopeOnDestroy).not.toHaveBeenCalled(); + expect(multiTrim(document.body.textContent)).toBe(''); + expect(scopeOnDestroy).not.toHaveBeenCalled(); - $rootScope.$apply('destroyFromNg1 = false'); + $rootScope.$apply('destroyFromNg1 = false'); - expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B'); - expect(scopeOnDestroy).not.toHaveBeenCalled(); + expect(multiTrim(document.body.textContent)).toBe('ng1A | ng1B'); + expect(scopeOnDestroy).not.toHaveBeenCalled(); - $rootScope.$apply('destroyFromNg2 = true'); + $rootScope.$apply('destroyFromNg2 = true'); - expect(multiTrim(document.body.textContent)).toBe(''); - expect(scopeOnDestroy).not.toHaveBeenCalled(); - }); - })); + expect(multiTrim(document.body.textContent)).toBe(''); + expect(scopeOnDestroy).not.toHaveBeenCalled(); + }); - it('should be called in order `$onChanges()` > `$onInit()` > `$doCheck()` > `$postLink()`', waitForAsync(() => { + it('should be called in order `$onChanges()` > `$onInit()` > `$doCheck()` > `$postLink()`', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = { // `$doCheck()` will keep getting called as long as the interpolated value keeps @@ -4085,16 +4031,13 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe( - '$onChanges > $onInit > $doCheck > $postLink', - ); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe('$onChanges > $onInit > $doCheck > $postLink'); + }); }); describe('destroying the upgraded component', () => { - it('should destroy `$componentScope`', waitForAsync(() => { + it('should destroy `$componentScope`', async () => { const scopeDestroyListener = jasmine.createSpy('scopeDestroyListener'); let ng2ComponentAInstance: Ng2ComponentA; @@ -4159,17 +4102,16 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(scopeDestroyListener).not.toHaveBeenCalled(); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(scopeDestroyListener).not.toHaveBeenCalled(); - ng2ComponentAInstance.destroyIt = true; - $digest(adapter); + ng2ComponentAInstance!.destroyIt = true; + $digest(adapter); - expect(scopeDestroyListener).toHaveBeenCalledTimes(1); - }); - })); + expect(scopeDestroyListener).toHaveBeenCalledTimes(1); + }); - it('should emit `$destroy` on `$element` and descendants', waitForAsync(() => { + it('should emit `$destroy` on `$element` and descendants', async () => { const elementDestroyListener = jasmine.createSpy('elementDestroyListener'); const descendantDestroyListener = jasmine.createSpy('descendantDestroyListener'); let ng2ComponentAInstance: Ng2ComponentA; @@ -4237,19 +4179,18 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(elementDestroyListener).not.toHaveBeenCalled(); - expect(descendantDestroyListener).not.toHaveBeenCalled(); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(elementDestroyListener).not.toHaveBeenCalled(); + expect(descendantDestroyListener).not.toHaveBeenCalled(); - ng2ComponentAInstance.destroyIt = true; - $digest(adapter); + ng2ComponentAInstance!.destroyIt = true; + $digest(adapter); - expect(elementDestroyListener).toHaveBeenCalledTimes(1); - expect(descendantDestroyListener).toHaveBeenCalledTimes(1); - }); - })); + expect(elementDestroyListener).toHaveBeenCalledTimes(1); + expect(descendantDestroyListener).toHaveBeenCalledTimes(1); + }); - it('should clear data on `$element` and descendants`', waitForAsync(() => { + it('should clear data on `$element` and descendants`', async () => { let ng1ComponentElement: angular.IAugmentedJQuery; let ng2ComponentAInstance: Ng2ComponentA; @@ -4318,19 +4259,18 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - expect(ng1ComponentElement.data!('test')).toBe(1); - expect(ng1ComponentElement.contents!().data!('test')).toBe(2); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(ng1ComponentElement!.data!('test')).toBe(1); + expect(ng1ComponentElement!.contents!().data!('test')).toBe(2); - ng2ComponentAInstance.destroyIt = true; - $digest(adapter); + ng2ComponentAInstance!.destroyIt = true; + $digest(adapter); - expect(ng1ComponentElement.data!('test')).toBeUndefined(); - expect(ng1ComponentElement.contents!().data!('test')).toBeUndefined(); - }); - })); + expect(ng1ComponentElement!.data!('test')).toBeUndefined(); + expect(ng1ComponentElement!.contents!().data!('test')).toBeUndefined(); + }); - it('should clear dom listeners on `$element` and descendants`', waitForAsync(() => { + it('should clear dom listeners on `$element` and descendants`', async () => { const elementClickListener = jasmine.createSpy('elementClickListener'); const descendantClickListener = jasmine.createSpy('descendantClickListener'); let ng1DescendantElement: angular.IAugmentedJQuery; @@ -4401,21 +4341,20 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - (ng1DescendantElement[0] as HTMLElement).click(); - expect(elementClickListener).toHaveBeenCalledTimes(1); - expect(descendantClickListener).toHaveBeenCalledTimes(1); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + (ng1DescendantElement![0] as HTMLElement).click(); + expect(elementClickListener).toHaveBeenCalledTimes(1); + expect(descendantClickListener).toHaveBeenCalledTimes(1); - ng2ComponentAInstance.destroyIt = true; - $digest(adapter); + ng2ComponentAInstance!.destroyIt = true; + $digest(adapter); - (ng1DescendantElement[0] as HTMLElement).click(); - expect(elementClickListener).toHaveBeenCalledTimes(1); - expect(descendantClickListener).toHaveBeenCalledTimes(1); - }); - })); + (ng1DescendantElement![0] as HTMLElement).click(); + expect(elementClickListener).toHaveBeenCalledTimes(1); + expect(descendantClickListener).toHaveBeenCalledTimes(1); + }); - it('should clean up `$doCheck()` watchers from the parent scope', waitForAsync(() => { + it('should clean up `$doCheck()` watchers from the parent scope', async () => { let ng2Component: Ng2Component; // Define `ng1Component` @@ -4469,32 +4408,30 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - const getWatcherCount: () => number = () => - (ng2Component.$scope as any).$$watchers.length; - const baseWatcherCount = getWatcherCount(); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + const getWatcherCount: () => number = () => (ng2Component!.$scope as any).$$watchers.length; + const baseWatcherCount = getWatcherCount(); - expect(multiTrim(document.body.textContent)).toBe(''); + expect(multiTrim(document.body.textContent)).toBe(''); - ng2Component.doShow = true; - $digest(adapter); - expect(multiTrim(document.body.textContent)).toBe('ng1'); - expect(getWatcherCount()).toBe(baseWatcherCount + 1); + ng2Component!.doShow = true; + $digest(adapter); + expect(multiTrim(document.body.textContent)).toBe('ng1'); + expect(getWatcherCount()).toBe(baseWatcherCount + 1); - ng2Component.doShow = false; - $digest(adapter); - expect(multiTrim(document.body.textContent)).toBe(''); - expect(getWatcherCount()).toBe(baseWatcherCount); + ng2Component!.doShow = false; + $digest(adapter); + expect(multiTrim(document.body.textContent)).toBe(''); + expect(getWatcherCount()).toBe(baseWatcherCount); - ng2Component.doShow = true; - $digest(adapter); - expect(multiTrim(document.body.textContent)).toBe('ng1'); - expect(getWatcherCount()).toBe(baseWatcherCount + 1); - }); - })); + ng2Component!.doShow = true; + $digest(adapter); + expect(multiTrim(document.body.textContent)).toBe('ng1'); + expect(getWatcherCount()).toBe(baseWatcherCount + 1); + }); }); - it('should support ng2 > ng1 > ng2 (no inputs/outputs)', waitForAsync(() => { + it('should support ng2 > ng1 > ng2 (no inputs/outputs)', async () => { // Define `ng1Component` const ng1Component: angular.IComponent = {template: 'ng1X()'}; @@ -4546,12 +4483,11 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(document.body.textContent)).toBe('ng2A(ng1X(ng2B))'); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toBe('ng2A(ng1X(ng2B))'); + }); - it('should support ng2 > ng1 > ng2 (with inputs/outputs)', fakeAsync(() => { + it('should support ng2 > ng1 > ng2 (with inputs/outputs)', async () => { let ng2ComponentAInstance: Ng2ComponentA; let ng2ComponentBInstance: Ng2ComponentB; let ng1ControllerXInstance: Ng1ControllerX; @@ -4666,103 +4602,102 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then((adapter) => { - // Initial value propagation. - // (ng2A > ng1X > ng2B) - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(foo, bar, baz) | ng1X(foo, bar, baz) | ng2B(foo, baz)', - ); + const adapter = await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + // Initial value propagation. + // (ng2A > ng1X > ng2B) + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(foo, bar, baz) | ng1X(foo, bar, baz) | ng2B(foo, baz)', + ); - // Update `ng2BInputA`/`ng2BInputC`. - // (Should not propagate upwards.) - ng2ComponentBInstance.ng2BInputA = 'foo2'; - ng2ComponentBInstance.ng2BInputC = 'baz2'; - $digest(adapter); - tick(); + // Update `ng2BInputA`/`ng2BInputC`. + // (Should not propagate upwards.) + ng2ComponentBInstance!.ng2BInputA = 'foo2'; + ng2ComponentBInstance!.ng2BInputC = 'baz2'; + $digest(adapter); + await timeout(); - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(foo, bar, baz) | ng1X(foo, bar, baz) | ng2B(foo2, baz2)', - ); + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(foo, bar, baz) | ng1X(foo, bar, baz) | ng2B(foo2, baz2)', + ); - // Emit from `ng2BOutputC`. - // (Should propagate all the way up to `ng1ADataC` and back all the way down to - // `ng2BInputC`.) - ng2ComponentBInstance.ng2BOutputC.emit('baz3'); - $digest(adapter); - tick(); + // Emit from `ng2BOutputC`. + // (Should propagate all the way up to `ng1ADataC` and back all the way down to + // `ng2BInputC`.) + ng2ComponentBInstance!.ng2BOutputC.emit('baz3'); + $digest(adapter); + await timeout(); - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(foo, bar, baz3) | ng1X(foo, bar, baz3) | ng2B(foo2, baz3)', - ); + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(foo, bar, baz3) | ng1X(foo, bar, baz3) | ng2B(foo2, baz3)', + ); - // Update `ng1XInputA`/`ng1XInputB`. - // (Should not propagate upwards, only downwards.) - ng1ControllerXInstance.ng1XInputA = 'foo4'; - ng1ControllerXInstance.ng1XInputB = {value: 'bar4'}; - $digest(adapter); - tick(); + // Update `ng1XInputA`/`ng1XInputB`. + // (Should not propagate upwards, only downwards.) + ng1ControllerXInstance!.ng1XInputA = 'foo4'; + ng1ControllerXInstance!.ng1XInputB = {value: 'bar4'}; + $digest(adapter); + await timeout(); - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(foo, bar, baz3) | ng1X(foo4, bar4, baz3) | ng2B(foo4, baz3)', - ); + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(foo, bar, baz3) | ng1X(foo4, bar4, baz3) | ng2B(foo4, baz3)', + ); - // Update `ng1XInputC`. - // (Should propagate upwards and downwards.) - ng1ControllerXInstance.ng1XInputC = {value: 'baz5'}; - $digest(adapter); - tick(); + // Update `ng1XInputC`. + // (Should propagate upwards and downwards.) + ng1ControllerXInstance!.ng1XInputC = {value: 'baz5'}; + $digest(adapter); + await timeout(); - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(foo, bar, baz5) | ng1X(foo4, bar4, baz5) | ng2B(foo4, baz5)', - ); + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(foo, bar, baz5) | ng1X(foo4, bar4, baz5) | ng2B(foo4, baz5)', + ); - // Update a property on `ng1XInputC`. - // (Should propagate upwards and downwards.) - ng1ControllerXInstance.ng1XInputC.value = 'baz6'; - $digest(adapter); - tick(); + // Update a property on `ng1XInputC`. + // (Should propagate upwards and downwards.) + ng1ControllerXInstance!.ng1XInputC.value = 'baz6'; + $digest(adapter); + await timeout(); - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(foo, bar, baz6) | ng1X(foo4, bar4, baz6) | ng2B(foo4, baz6)', - ); + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(foo, bar, baz6) | ng1X(foo4, bar4, baz6) | ng2B(foo4, baz6)', + ); - // Emit from `ng1XOutputA`. - // (Should propagate upwards to `ng1ADataA` and back all the way down to - // `ng2BInputA`.) - (ng1ControllerXInstance as any).ng1XOutputA({value: 'foo7'}); - $digest(adapter); - tick(); + // Emit from `ng1XOutputA`. + // (Should propagate upwards to `ng1ADataA` and back all the way down to + // `ng2BInputA`.) + (ng1ControllerXInstance! as any).ng1XOutputA({value: 'foo7'}); + $digest(adapter); + await timeout(); - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(foo7, bar, baz6) | ng1X(foo7, bar4, baz6) | ng2B(foo7, baz6)', - ); + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(foo7, bar, baz6) | ng1X(foo7, bar4, baz6) | ng2B(foo7, baz6)', + ); - // Emit from `ng1XOutputB`. - // (Should propagate upwards to `ng1ADataB`, but not downwards, - // since `ng1XInputB` has been re-assigned (i.e. `ng2ADataB !== ng1XInputB`).) - (ng1ControllerXInstance as any).ng1XOutputB('bar8'); - $digest(adapter); - tick(); + // Emit from `ng1XOutputB`. + // (Should propagate upwards to `ng1ADataB`, but not downwards, + // since `ng1XInputB` has been re-assigned (i.e. `ng2ADataB !== ng1XInputB`).) + (ng1ControllerXInstance! as any).ng1XOutputB('bar8'); + $digest(adapter); + await timeout(); - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(foo7, bar8, baz6) | ng1X(foo7, bar4, baz6) | ng2B(foo7, baz6)', - ); + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(foo7, bar8, baz6) | ng1X(foo7, bar4, baz6) | ng2B(foo7, baz6)', + ); - // Update `ng2ADataA`/`ng2ADataB`/`ng2ADataC`. - // (Should propagate everywhere.) - ng2ComponentAInstance.ng2ADataA = {value: 'foo9'}; - ng2ComponentAInstance.ng2ADataB = {value: 'bar9'}; - ng2ComponentAInstance.ng2ADataC = {value: 'baz9'}; - $digest(adapter); - tick(); + // Update `ng2ADataA`/`ng2ADataB`/`ng2ADataC`. + // (Should propagate everywhere.) + ng2ComponentAInstance!.ng2ADataA = {value: 'foo9'}; + ng2ComponentAInstance!.ng2ADataB = {value: 'bar9'}; + ng2ComponentAInstance!.ng2ADataC = {value: 'baz9'}; + $digest(adapter); + await timeout(); - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(foo9, bar9, baz9) | ng1X(foo9, bar9, baz9) | ng2B(foo9, baz9)', - ); - }); - })); + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(foo9, bar9, baz9) | ng1X(foo9, bar9, baz9) | ng2B(foo9, baz9)', + ); + }); - it('should support ng2 > ng1 > ng2 > ng1 (with `require`)', waitForAsync(() => { + it('should support ng2 > ng1 > ng2 > ng1 (with `require`)', async () => { // Define `ng1Component` const ng1ComponentA: angular.IComponent = { template: 'ng1A()', @@ -4839,15 +4774,14 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(document.body.textContent)).toBe( - 'ng2A(ng1A(ng2B(ng1B(^^ng1A: ng1A | ?^^ng1B: | ^ng1B: ng1B))))', - ); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(document.body.textContent)).toBe( + 'ng2A(ng1A(ng2B(ng1B(^^ng1A: ng1A | ?^^ng1B: | ^ng1B: ng1B))))', + ); + }); describe('standalone', () => { - it('should upgrade to a standalone component in NgModule-bootstrapped application', waitForAsync(() => { + it('should upgrade to a standalone component in NgModule-bootstrapped application', async () => { const ng1Component: angular.IComponent = {template: `I'm from AngularJS!`}; // Define `Ng1ComponentFacade` (standalone) @@ -4885,10 +4819,9 @@ withEachNg1Version(() => { // Bootstrap const element = html(``); - bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module).then(() => { - expect(multiTrim(element.textContent)).toBe(`I'm from AngularJS!`); - }); - })); + await bootstrap(platformBrowserDynamic(), Ng2Module, element, ng1Module); + expect(multiTrim(element.textContent)).toBe(`I'm from AngularJS!`); + }); }); }); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 426a4e690c9..11f8c0a3211 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,6 +6,9 @@ importers: .: configDependencies: {} packageManagerDependencies: + '@pnpm/exe': + specifier: 12.11.2 + version: 12.11.2 pnpm: specifier: 12.11.2 version: 12.11.2 @@ -89,6 +92,11 @@ packages: cpu: [x64] os: [win32] + '@pnpm/exe@12.11.2': + resolution: {integrity: sha512-uUudrvXShgp6yYRL/6XjeB2B2kbjE/alBdVWjFBP0jDiOnV5R83OpCWuGtc+Tn4stk0DEgO/x+vhEUTUf4x+Yw==} + engines: {node: '>=18.*'} + hasBin: true + pnpm@12.11.2: resolution: {integrity: sha512-JaUWUqGWeFr18ovabf6NxYLr76SsHRgCIc4TkCMcX7dmN4IupLbkYzznSs3LCnf3Ja8RutOBd/3t2u6BipVcuQ==} engines: {node: '>=18.*'} @@ -138,6 +146,23 @@ snapshots: '@pnpm/exe.win32-x64@12.11.2': optional: true + '@pnpm/exe@12.11.2': + optionalDependencies: + '@pnpm/exe.android-arm64': 12.11.2 + '@pnpm/exe.android-x64': 12.11.2 + '@pnpm/exe.darwin-arm64': 12.11.2 + '@pnpm/exe.darwin-x64': 12.11.2 + '@pnpm/exe.freebsd-x64': 12.11.2 + '@pnpm/exe.linux-arm64': 12.11.2 + '@pnpm/exe.linux-arm64-musl': 12.11.2 + '@pnpm/exe.linux-ppc64': 12.11.2 + '@pnpm/exe.linux-riscv64': 12.11.2 + '@pnpm/exe.linux-s390x': 12.11.2 + '@pnpm/exe.linux-x64': 12.11.2 + '@pnpm/exe.linux-x64-musl': 12.11.2 + '@pnpm/exe.win32-arm64': 12.11.2 + '@pnpm/exe.win32-x64': 12.11.2 + pnpm@12.11.2: optionalDependencies: '@pnpm/exe.android-arm64': 12.11.2 @@ -270,8 +295,8 @@ importers: specifier: ^1.0.5 version: 1.0.7 '@types/jasmine': - specifier: ^6.0.0 - version: 6.0.0 + specifier: ^7.0.0 + version: 7.0.0 '@types/jasminewd2': specifier: ^2.0.8 version: 2.0.13 @@ -327,11 +352,11 @@ importers: specifier: ^14.0.0 version: 14.1.1(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0) jasmine: - specifier: 6.3.0 - version: 6.3.0 + specifier: 7.0.0 + version: 7.0.0 jasmine-core: - specifier: 6.3.0 - version: 6.3.0 + specifier: 7.0.2 + version: 7.0.2 jasmine-reporters: specifier: ^2.5.2 version: 2.5.2 @@ -464,7 +489,7 @@ importers: version: 2.2.1(supports-color@11.0.0) karma-jasmine-html-reporter: specifier: ^2.2.0 - version: 2.3.0(jasmine-core@6.3.0)(karma-jasmine@5.1.0(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)))(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)) + version: 2.3.0(jasmine-core@7.0.2)(karma-jasmine@5.1.0(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)))(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)) prettier: specifier: ^3.8.0 version: 3.9.10 @@ -640,8 +665,8 @@ importers: specifier: 1.0.7 version: 1.0.7 '@types/jasmine': - specifier: 6.0.0 - version: 6.0.0 + specifier: 7.0.0 + version: 7.0.0 '@types/jsdom': specifier: 30.0.0 version: 30.0.0 @@ -703,8 +728,8 @@ importers: specifier: ^3.0.0 version: 3.0.0 jasmine-core: - specifier: 6.3.0 - version: 6.3.0 + specifier: 7.0.2 + version: 7.0.2 jsdom: specifier: 30.1.2 version: 30.1.2 @@ -719,7 +744,7 @@ importers: version: 5.1.0(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)) karma-jasmine-html-reporter: specifier: 2.3.0 - version: 2.3.0(jasmine-core@6.3.0)(karma-jasmine@5.1.0(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)))(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)) + version: 2.3.0(jasmine-core@7.0.2)(karma-jasmine@5.1.0(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)))(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)) marked: specifier: 18.1.1 version: 18.1.1 @@ -1018,8 +1043,8 @@ importers: specifier: workspace:* version: link:../packages/upgrade '@types/jasmine': - specifier: 6.0.0 - version: 6.0.0 + specifier: 7.0.0 + version: 7.0.0 '@types/jasminewd2': specifier: 2.0.13 version: 2.0.13 @@ -1079,8 +1104,8 @@ importers: version: 3.2.0 devDependencies: '@types/jasmine': - specifier: ^6.0.0 - version: 6.0.0 + specifier: ^7.0.0 + version: 7.0.0 '@types/node': specifier: ^20.14.8 version: 20.19.43 @@ -1564,8 +1589,8 @@ importers: version: 6.0.3 devDependencies: '@types/jasmine': - specifier: ~6.0.0 - version: 6.0.0 + specifier: ~7.0.0 + version: 7.0.0 '@types/jasmine-reporters': specifier: ~2.5.3 version: 2.5.3 @@ -1582,11 +1607,11 @@ importers: specifier: ~4.0.0 version: 4.0.0(supports-color@11.0.0) jasmine: - specifier: 6.3.0 - version: 6.3.0 + specifier: 7.0.0 + version: 7.0.0 jasmine-core: - specifier: 6.3.0 - version: 6.3.0 + specifier: 7.0.2 + version: 7.0.2 jasmine-reporters: specifier: ~2.5.2 version: 2.5.2 @@ -4639,6 +4664,9 @@ packages: '@types/jasmine@6.0.0': resolution: {integrity: sha512-18lgGsLmEh3VJk9eZ5wAjTISxdqzl6YOwu8UdMpolajN57QOCNbl+AbHUd+Yu9ItrsFdB+c8LSZSGNg8nHaguw==} + '@types/jasmine@7.0.0': + resolution: {integrity: sha512-6yNx9BsBSKiXO2yqLXs/GZDuD58Gkn6Ty26254FFOuw6B4XU5Xq8mAR0xFy8zHgAhqQd++y41fSJ8BdwrWXhqQ==} + '@types/jasminewd2@2.0.13': resolution: {integrity: sha512-aJ3wj8tXMpBrzQ5ghIaqMisD8C3FIrcO6sDKHqFbuqAsI7yOxj0fA7MrRCPLZHIVUjERIwsMmGn/vB0UQ9u0Hg==} @@ -14691,13 +14719,15 @@ snapshots: '@types/jasmine-reporters@2.5.3': dependencies: - '@types/jasmine': 6.0.0 + '@types/jasmine': 7.0.0 '@types/jasmine@6.0.0': {} + '@types/jasmine@7.0.0': {} + '@types/jasminewd2@2.0.13': dependencies: - '@types/jasmine': 6.0.0 + '@types/jasmine': 7.0.0 '@types/jsdom@21.1.7': dependencies: @@ -18925,9 +18955,9 @@ snapshots: is-wsl: 2.2.0 which: 3.0.1 - karma-jasmine-html-reporter@2.3.0(jasmine-core@6.3.0)(karma-jasmine@5.1.0(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)))(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)): + karma-jasmine-html-reporter@2.3.0(jasmine-core@7.0.2)(karma-jasmine@5.1.0(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)))(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)): dependencies: - jasmine-core: 6.3.0 + jasmine-core: 7.0.2 karma: 6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6) karma-jasmine: 5.1.0(karma@6.4.4(bufferutil@4.1.0)(debug@4.4.3(supports-color@11.0.0))(supports-color@11.0.0)(utf-8-validate@6.0.6)) diff --git a/tools/testing/zone_base_setup.mts b/tools/testing/zone_base_setup.mts index 13c0ca194aa..168687b377b 100644 --- a/tools/testing/zone_base_setup.mts +++ b/tools/testing/zone_base_setup.mts @@ -14,4 +14,3 @@ import 'zone.js/plugins/proxy'; import 'zone.js/plugins/sync-test'; import 'zone.js/plugins/async-test'; import 'zone.js/plugins/fake-async-test'; -import 'zone.js/plugins/jasmine-patch'; diff --git a/vscode-ng-language-service/package.json b/vscode-ng-language-service/package.json index 14bfb323562..5e42ffef7dd 100644 --- a/vscode-ng-language-service/package.json +++ b/vscode-ng-language-service/package.json @@ -411,14 +411,14 @@ "typescript": "6.0.3" }, "devDependencies": { - "@types/jasmine": "~6.0.0", + "@types/jasmine": "~7.0.0", "@types/jasmine-reporters": "~2.5.3", "@types/node": "^24.5.2", "@types/vscode": "^1.74.3", "@vscode/test-electron": "~3.1.0", "@vscode/vsce": "~4.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", "source-map-support": "^0.5.21", "vscode-jsonrpc": "8.2.0",