Skip to content

Commit 9248874

Browse files
committed
test(core): add test validating that component destroy does not depend on the injector
While developing this feature, I attempted to inject a service during component destruction (to call `SharedStylesHost.prototype.removeHost`), however this broke some Material use cases which seem to destroy the injector before the component. Whether this constraint was intended or not, I believe we currently live in a world where component destruction cannot depend on its injection, so I'm enforcing this in a test to be clear about that constraint. This is not intended to imply that this is a _good_ constraint or that we _want_ this to be the case, but it does represent the reality we currently exist in.
1 parent adc8668 commit 9248874

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

packages/core/test/acceptance/view_container_ref_spec.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,46 @@ describe('ViewContainerRef', () => {
703703
});
704704
});
705705

706+
describe('destroy', () => {
707+
// NOTE: We may not necessarily _want_ this to be the case, but it does seem to be necessary
708+
// for some amount of Angular code out there. We may want to consider lifting this constraint.
709+
it('should not throw if the injector is destroyed before a view is removed', () => {
710+
@Component({
711+
template: 'View Content',
712+
standalone: false,
713+
})
714+
class DynamicComponent {}
715+
716+
@Component({
717+
template: '<ng-container #vcr></ng-container>',
718+
standalone: false,
719+
})
720+
class App {
721+
@ViewChild('vcr', {read: ViewContainerRef, static: true})
722+
vcr!: ViewContainerRef;
723+
}
724+
725+
TestBed.configureTestingModule({declarations: [App, DynamicComponent]});
726+
727+
const envInjector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector));
728+
const fixture = TestBed.createComponent(App);
729+
fixture.detectChanges();
730+
731+
const componentRef = fixture.componentInstance.vcr.createComponent(DynamicComponent, {
732+
environmentInjector: envInjector,
733+
});
734+
fixture.detectChanges();
735+
736+
// Destroy the environment injector first
737+
envInjector.destroy();
738+
739+
// Should be able to destroy the component afterwards.
740+
expect(() => {
741+
componentRef.destroy();
742+
}).not.toThrow();
743+
});
744+
});
745+
706746
describe('length', () => {
707747
it('should return the number of embedded views', () => {
708748
TestBed.configureTestingModule({declarations: [EmbeddedViewInsertionComp, VCRefDirective]});

0 commit comments

Comments
 (0)