【问题标题】:Unit tests if all subscriptions have been cleared in Angular/Redux单元测试是否已在 Angular/Redux 中清除所有订阅
【发布时间】:2019-01-01 18:18:18
【问题描述】:
我有一个使用 ngrx 的 Angular 应用程序,并且我正在使用带有主题的 takeUntil 方法,以便在组件被销毁时清除订阅。
private unsubscribe$ = new Subject();
this.store.select(actions.getTest)
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe((numberOfSelectedRoles: number) => {
});
ngOnDestroy() {
this.unsubscribe$.next(true);
}
我决定使用这种方法而不是保留订阅数组,因为它看起来更干净,但是有没有办法在 Jasmine 中编写单元测试来检查组件是否没有开放订阅?
【问题讨论】:
标签:
angular
unit-testing
ngrx
subscription
【解决方案1】:
我们使用 takeWhile 和一个标志来代替。这可能更容易测试,因为您可以只检查标志的值。
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Product } from '../product';
import { Observable } from 'rxjs';
import { takeWhile } from 'rxjs/operators';
/* NgRx */
import { Store, select } from '@ngrx/store';
@Component({
selector: 'pm-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit, OnDestroy {
componentActive = true;
// Used to highlight the selected product in the list
selectedProduct: Product | null;
constructor(private store: Store<fromProduct.State>) { }
ngOnInit(): void {
// Subscribe here because it does not use an async pipe
this.store.pipe(
select(fromProduct.getCurrentProduct),
takeWhile(() => this.componentActive)
).subscribe(
currentProduct => this.selectedProduct = currentProduct
);
}
ngOnDestroy(): void {
this.componentActive = false;
}
}