[英]How to mock a service call in a function in angular unit testing?
I am trying to write a test case for the following function: 我正在尝试为以下功能编写测试用例:
foo = () => {
this.someService.getDetails({key:'value'}).subscribe(details => {
//do stuff
this.someService.getMoreDetails().subscribe(moreDetails => {
//do stuff
});
});
}
The service looks like this: 该服务如下所示:
getDetails = (args) :Observable<any> {
return this.http.post<any>(//calls)
}
// similar for getMoreDetails
The test file that I have written looks like this: 我编写的测试文件如下所示:
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();
});
However, my test case fails giving the error 'Cannot read property subscribe of undefined' (for the first line inside foo function). 但是,我的测试用例未能给出错误“无法读取未定义的属性订阅”(对于foo函数中的第一行)。
I have tried using mockservice classes too but the same error comes up. 我也尝试过使用模拟服务类,但出现相同的错误。 What is the possible reason for this and how can I solve it?
可能的原因是什么,我该如何解决?
You start by calling the foo()
function, which calls the getDetails()
method of the service. 首先调用
foo()
函数,该函数调用服务的getDetails()
方法。 This method is a spy, and you have never told the spy what to return, so it returns undefined. 此方法是间谍,您从未告诉过间谍该返回什么,因此它返回的是undefined。
Then, you tell the spy what to return. 然后,您告诉间谍返回什么。 That's too late: the service call has already been made.
为时已晚:已经进行了服务呼叫。 Tell the spy what to return before calling
foo()
. 在调用
foo()
之前,告诉间谍返回什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.