我正在尝试为以下函数编写一个测试用例:
foo = () => {
this.someService.getDetails({key:'value'}).subscribe(details => {
//do stuff
this.someService.getMoreDetails().subscribe(moreDetails => {
//do stuff
});
});
}
该服务如下所示:
getDetails = (args) :Observable<any> {
return this.http.post<any>(//calls)
}
// similar for getMoreDetails
我编写的测试文件如下所示:
const someServiceStub = jasmine.createSpyObj('someService', ['getDetails', 'getMoreDetails']);
...
...
it('should called getMoreDetails', () => {
component.foo();
fixture.detectChanges();
someServiceStub.getDetails.and.returnValue(Observable.of
({ Details: 'Tired of giving you details'})
);
expect(someServiceStub.getMoreDetails).toHaveBeenCalled();
});
但是,我的测试用例失败,并给出错误“无法读取未定义的属性订阅”(对于 foo 函数内的第一行)。
我也尝试过使用模拟服务类,但出现了同样的错误。 可能的原因是什么以及如何解决?
最佳答案
首先调用 foo()
函数,该函数调用服务的 getDetails()
方法。这个方法是一个 spy ,你从来没有告诉 spy 要返回什么,所以它返回未定义。
然后,你告诉 spy 要返回什么。已经太晚了:服务电话已经打了。告诉 spy 在调用foo()
之前返回什么。
关于angular - 如何在 Angular 单元测试中模拟函数中的服务调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54050891/