【发布时间】:2019-01-29 11:42:21
【问题描述】:
我正在尝试测试一个取消订阅所有订阅的函数:
ngOnDestroy() {
this.tryUnsubscribe(this.carsSubscription);
this.tryUnsubscribe(this.partsSubscription);
this.tryUnsubscribe(this.shopsSubscription);
}
这是我为函数写的测试:
it('should unsubscribe from subscriptions ', () => {
spyOn(component, "tryUnsubscribe");
component.ngOnDestroy();
expect(component.tryUnsubscribe).toHaveBeenCalledWith(component['carsSubscription']);
expect(component.tryUnsubscribe).toHaveBeenCalledWith(component['partsSubscription']);
expect(component.tryUnsubscribe).toHaveBeenCalledWith(component['shopsSubscription']);
});
问题:
如果我注释掉一个函数调用,测试仍然通过。
ngOnDestroy() {
this.tryUnsubscribe(this.carsSubscription);
//this.tryUnsubscribe(this.partsSubscription);
this.tryUnsubscribe(this.shopsSubscription);
}
只有当我注释掉所有这些函数调用时,测试才会失败:
ngOnDestroy() {
//this.tryUnsubscribe(this.carsSubscription);
//this.tryUnsubscribe(this.partsSubscription);
//this.tryUnsubscribe(this.shopsSubscription);
}
如何正确测试这种功能?我做错了什么?
【问题讨论】:
-
你能在断言之前注销所有
component['...']吗? -
@Buczkowski 他们都注销 undefined,因为我只是在组件的 TS 代码中创建订阅时才定义这些订阅。
-
这就是为什么即使你注释掉一些方法执行它也会通过的原因。它将像使用
undefined调用一样被断言。用调用时间检查它怎么样?像 tryUnsubscribe 被调用了 3 次? -
好的,你能提供一个代码示例的答案吗?我会投票赞成,如果今天没有人提出更好的解决方案,我会将其标记为正确答案。