基本上,我想检查在调用ngOnDestroy后是否有任何有效的订阅。目前,该代码将所有订阅收集到组件的属性数组中,并在ngOnDestroy上取消订阅。我很容易忘记将新创建的订阅添加到此数组中。希望编写一个测试来帮助我消除这种情况。
基本上,我想检查在调用ngOnDestroy后是否有任何有效的订阅。目前,该代码将所有订阅收集到组件的属性数组中,并在ngOnDestroy上取消订阅。我很容易忘记将新创建的订阅添加到此数组中。希望编写一个测试来帮助我消除这种情况。
我不确定您是想测试ngOnDestroy方法是否结束了在公共可观察对象上启动的外部订阅,还是想查看组件中是否有任何杂散的内部订阅。
如果是前者,您可以编写以下测试:
it('should end subscriptions when the component is destroyed', () => {
// Setup the spies
const spy = jasmine.createSpy();
const noop = () => {};
// Start the subscriptions
const streams = [component.streamOne$, component.streamTwo$, component.streamThree$];
streams.forEach(stream => stream.subscribe(noop, noop, spy));
// Destroy the component
component.ngOnDestroy();
// Verify the spy was called three times (once for each subscription)
expect(spy).toHaveBeenCalledTimes(streams.length);
});
import { setup, track, printSubscribers } from 'observable-profiler';
describe('MyComponent', () => {
beforeAll(() => {
setup(Observable);
});
it('should not have any stray subscriptions', () => {
track();
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
fixture.destroy()
const subscriptions = track(false);
expect(subscriptions).toBeUndefined();
});
...
你可以做一个简单的技巧,在每个订阅中增加服务中的一个值,并在每个取消订阅中减少它,然后您可以检查如果值为0,则没有任何订阅保持活动状态
mysubscription.subscribe( data => { this.myService.myValue++;})
mysubscription.unsubscribe( data => { this.myService.myValue--;})