尝试在另一个服务调用的订阅()中测试服务调用
我的目标是测试是否已在服务呼叫的成功中调用其他服务的方法:
组件中的服务调用代码:
public myFunction(param: number): void {
this.subscriptions.push(
this.service1.service1Method(param).subscribe(
(response) => {
this.service2.service2Method({
param1: true,
param2: false
});
},
(error) => {
this.errorFunction();
}
)
);
}
单元测试:
it('should call 2nd service method upon 1st service method success', fakeAsync(() => {
const spyService1 = spyOn(service1, 'service1Method').and.returnValue(
of([]])
);
const spyService2 = spyOn(service2, 'service2Method');
component.myFunction(1);
tick();
expect(spyService1).toHaveBeenCalled();
expect(spyService2).toHaveBeenCalledWith({
param1: true,
param2: false
});
}));
控制台显示:
expect(spy).toHaveBeenCalledWith(...expected)
Expected: {"param1": true, "param2" false}
Number of calls: 0
注意:所有服务导入和样板都不包括在内,因为它没有显示任何错误我(我正在使用强大的覆盖物)。我写的代码块中显然存在一个逻辑错误,但没有使其正常工作。
My goal is to test whether another service's method has been called upon the success of a service call:
Service call code within component:
public myFunction(param: number): void {
this.subscriptions.push(
this.service1.service1Method(param).subscribe(
(response) => {
this.service2.service2Method({
param1: true,
param2: false
});
},
(error) => {
this.errorFunction();
}
)
);
}
unit test:
it('should call 2nd service method upon 1st service method success', fakeAsync(() => {
const spyService1 = spyOn(service1, 'service1Method').and.returnValue(
of([]])
);
const spyService2 = spyOn(service2, 'service2Method');
component.myFunction(1);
tick();
expect(spyService1).toHaveBeenCalled();
expect(spyService2).toHaveBeenCalledWith({
param1: true,
param2: false
});
}));
The console shows:
expect(spy).toHaveBeenCalledWith(...expected)
Expected: {"param1": true, "param2" false}
Number of calls: 0
Note: all service imports and boilerplate isn't included because it shows no error for me (I'm using strong linting). There's obviously a logical error in this block of code I've written that isn't making it work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果Service2Method返回可观察到的可观察,则需要订阅以实际致电。在当前实施中,您从未订阅过它,因此此方法从未被调用。
您可以在现有的订阅中添加另一个订阅(这是一种不良方法,但会起作用),也可以使用扁平的操作员(SwitchMap,Mergemap或任何其他)将单个订阅纳入您的功能中。
If the service2Method returns an observable, you need to subscribe to actually call if. In the current implementatation you never subscribed to it, so this method is never called.
You can either add another subscribe inside the existing one (which is a bad approach, but will work) or use a flattening operator (switchmap, mergemap or any other) to have a single subscribe into your function.