【问题标题】:How to test is all subscription unsubscribed in Angular?如何测试 Angular 中的所有订阅都取消订阅了吗?
【发布时间】:2019-07-02 11:02:50
【问题描述】:

基本上,我想在调用 ngOnDestroy 之后检查是否有任何活动订阅。现在,代码收集组件属性数组中的所有订阅,并在 ngOnDestroy 上取消订阅。我很容易忘记向这个数组添加一个新创建的订阅。想写一个测试来帮助我消除这种情况。

【问题讨论】:

标签: angular testing rxjs


【解决方案1】:

不确定您是否正在尝试测试 ngOnDestroy 方法是否正在结束在您的公共 observables 上从外部开始的订阅,或者您是否正在尝试查看组件中是否还有任何杂散的内部订阅。

对于前者,您可以编写如下测试:

  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);
  });

这将确保 ngOnDestroy 完成它应该做的事情并结束在该组件的公共 observables 上启动的任何订阅。

但是,如果您关心的是后者,那么检查杂散订阅的唯一方法是通过猴子修补 rxjs 中的 Observable。 This library does it well(我不隶属)。用它写一个测试很简单:

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();
  });
  ...

【讨论】:

  • 谢谢,德米特里!第二个解决方案看起来像我需要的。会试试的
【解决方案2】:

您可以制作一个简单的技巧,在每次订阅中增加服务中的值并在每次取消订阅中减少它,然后检查值是否为 0,因此没有订阅有效

mysubscription.subscribe( data => { this.myService.myValue++;})
mysubscription.unsubscribe( data => { this.myService.myValue--;})

【讨论】:

  • 这里一样——调用 subscribe 方法时很容易忘记这个值
猜你喜欢
  • 2019-02-11
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 2022-01-19
  • 2012-03-14
  • 2019-01-31
  • 1970-01-01
  • 2018-04-19
相关资源
最近更新 更多