|
8 | 8 |
|
9 | 9 | import {TestBed} from '../testing';
|
10 | 10 | import {ErrorHandler, provideBrowserGlobalErrorListeners} from '../src/error_handler';
|
11 |
| -import {isNode} from '@angular/private/testing'; |
| 11 | +import {isNode, withBody} from '@angular/private/testing'; |
| 12 | +import {ApplicationRef, Component, destroyPlatform, inject} from '../src/core'; |
| 13 | +import {bootstrapApplication} from '@angular/platform-browser'; |
12 | 14 |
|
13 | 15 | class MockConsole {
|
14 | 16 | res: any[][] = [];
|
@@ -65,4 +67,49 @@ describe('ErrorHandler', () => {
|
65 | 67 | expect(spy.calls.count()).toBe(1);
|
66 | 68 | window.onerror = originalWindowOnError;
|
67 | 69 | });
|
| 70 | + |
| 71 | + it( |
| 72 | + 'should not try to inject the `ErrorHandler` lazily once app is destroyed', |
| 73 | + withBody('<app></app>', async () => { |
| 74 | + destroyPlatform(); |
| 75 | + |
| 76 | + let dispatched = false; |
| 77 | + // Prevents Jasmine from reporting an error. |
| 78 | + const originalWindowOnError = window.onerror; |
| 79 | + window.onerror = () => {}; |
| 80 | + |
| 81 | + @Component({ |
| 82 | + selector: 'app', |
| 83 | + template: '', |
| 84 | + }) |
| 85 | + class App { |
| 86 | + constructor() { |
| 87 | + inject(ApplicationRef).onDestroy(() => { |
| 88 | + // Note: The unit test environment differs from the real browser environment. |
| 89 | + // This is a simple test that ensures that if an error event is dispatched |
| 90 | + // during destruction, it does not attempt to inject the `ErrorHandler`. |
| 91 | + // Before the `if (injector.destroyed)` checks were added, this would |
| 92 | + // throw a "destroyed injector" error. |
| 93 | + dispatched = window.dispatchEvent(new Event('error')); |
| 94 | + }); |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + const appRef = await bootstrapApplication(App, { |
| 99 | + providers: [provideBrowserGlobalErrorListeners()], |
| 100 | + }); |
| 101 | + appRef.destroy(); |
| 102 | + |
| 103 | + // We assert that `dispatched` is truthy because Angular's error handler |
| 104 | + // calls `preventDefault()` on the event object, which would cause `dispatchEvent` |
| 105 | + // to return false. This assertion ensures that Angular's error handler was not invoked. |
| 106 | + expect(dispatched).toEqual(true); |
| 107 | + |
| 108 | + // Wait until the error is re-thrown, so we can reset the original error handler. |
| 109 | + await new Promise((resolve) => setTimeout(resolve, 1)); |
| 110 | + |
| 111 | + window.onerror = originalWindowOnError; |
| 112 | + destroyPlatform(); |
| 113 | + }), |
| 114 | + ); |
68 | 115 | });
|
0 commit comments