ngOnDestroy
是 Angular 组件生命周期的一部分,它在组件即将被销毁时调用。如果你在 Jasmine 测试中遇到 ngOnDestroy
测试失败的问题,可能是由于以下几个原因:
Observable
订阅),确保在 ngOnDestroy
中取消这些订阅。TestBed
的配置。以下是一个简单的示例,展示如何测试 ngOnDestroy
方法:
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-example',
template: `<div>Example Component</div>`
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;
constructor() {
this.subscription = new Subscription();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ExampleComponent } from './example.component';
describe('ExampleComponent', () => {
let component: ExampleComponent;
let fixture: ComponentFixture<ExampleComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ExampleComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should unsubscribe on ngOnDestroy', () => {
spyOn(component.subscription, 'unsubscribe').and.callThrough();
component.ngOnDestroy();
expect(component.subscription.unsubscribe).toHaveBeenCalled();
});
});
ngOnDestroy
中正确取消订阅。takeUntil
操作符来管理订阅,这样可以在 ngOnDestroy
中更容易地取消所有订阅。import { Component, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-example',
template: `<div>Example Component</div>`
})
export class ExampleComponent implements OnDestroy {
private destroy$ = new Subject<void>();
constructor() {
someObservable$.pipe(takeUntil(this.destroy$)).subscribe();
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
TestBed
正确配置,并且在每个测试之前正确创建和销毁组件。beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ExampleComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
领取专属 10元无门槛券
手把手带您无忧上云