如何在 angular 单元测试中模拟函数中的服务调用?
How to mock a service call in a function in angular unit testing?
我正在尝试为以下功能编写测试用例:
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();
});
但是,我的测试用例失败并给出错误 'Cannot read property subscribe of undefined'(对于 foo 函数内的第一行)。
我也尝试过使用 mockservice 类,但出现了同样的错误。
这可能是什么原因,我该如何解决?
您首先调用 foo()
函数,该函数调用服务的 getDetails()
方法。这个方法是一个间谍,你从来没有告诉间谍要return做什么,所以它return是未定义的。
然后,你告诉间谍要做什么 return。为时已晚:已经进行了服务调用。告诉间谍 return 在 调用 foo()
之前要做什么。
我正在尝试为以下功能编写测试用例:
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();
});
但是,我的测试用例失败并给出错误 'Cannot read property subscribe of undefined'(对于 foo 函数内的第一行)。
我也尝试过使用 mockservice 类,但出现了同样的错误。 这可能是什么原因,我该如何解决?
您首先调用 foo()
函数,该函数调用服务的 getDetails()
方法。这个方法是一个间谍,你从来没有告诉间谍要return做什么,所以它return是未定义的。
然后,你告诉间谍要做什么 return。为时已晚:已经进行了服务调用。告诉间谍 return 在 调用 foo()
之前要做什么。