【发布时间】:2019-06-04 03:50:31
【问题描述】:
我已经为这个函数写了一个单元测试:
getCarsAndSetup(){
this.getCars();
this.getFactoryInfo();
}
这是 getCars() 函数:
getCars() {
const subscription = this.carDetailsService.getAll().subscribe((carDetails) => {
this.carInfoService.setCars(carDetails);
subscription.unsubscribe(); <-------------- Here the
subscription is undefined
when running the test,
however when running
the app, the subscription
is defined and
everything is fine
});
}
这是单元测试:
fdescribe('getCarsAndSetup', () => {
it('should get cars and set them up', () => {
component.getFactoriesAndUnsubscribe();
spyOn(component, "getCars");
spyOn(component, "getFactoryInfo");
expect(component.getCars).toHaveBeenCalled();
expect(component.getFactoryInfo).toHaveBeenCalled();
});
});
我正在使用 carDetailsService 的模拟。这是 carDetailsService 模拟中的 getAll() 方法:
getAll(): Observable<CarModel[]> {
return Observable.create((observer:any) => {
observer.next([]);
});
}
这与 REAL carDetailsService 中的方法相同:
getAll(): Observable<CarModel[]> {
return this.http.get<CarModel[]>(this.carUrl);
}
问题是当我运行应用程序本身时,在 getCars() 方法中定义了订阅,我可以取消订阅等等,一切都很好。
但是,当我运行测试时,此测试失败,因为由于某种原因,当我尝试取消订阅时,getCars() 函数中的订阅未定义。
仅在运行测试时未定义订阅的原因可能是什么?这可能与我嘲笑 carDetailsService 的 getAll() 函数的方式有关吗?
【问题讨论】:
-
你可以使用管道运算符 take(1) 吗?当您在收到数据后取消订阅时,take(1) 将取消订阅 Observable。另外,使用您的代码,您确定模拟的 observable 没有抛出错误吗?如果在订阅中添加错误参数,你会得到什么吗?我想知道您是否在出现错误时不取消订阅。
标签: angular unit-testing jasmine rxjs karma-jasmine