这是一个简单的post函数,我可以在jasmine中单元测试成功和catchError。能否在jasmine中测试finalize,即在finalize中,我们是否可以期望装载机被关闭?
post(url,requestData){
this.http.post(url, requestData).pipe(
response => this.Response(response),
catchError((error: Response) => this.Error(error, msg)),
finalize(() => {
loader.close();
})
}
在finalize中,我正在关闭加载器。我需要对在finalize中调用的关闭加载器进行单元测试。
我也在努力解决同样的问题。在我的案例中,我试图测试Angular中的拦截器。
我的解决方案是通过一个真实的Observable作为mock。
这是我的实际代码。
@Injectable()
export class SetLoadingService implements HttpInterceptor {
constructor(@Inject('INotificationLoading') private _INotificationLoading: INotificationLoading) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.has('HideLoading')) {
return next.handle(req);
} else {
this._INotificationLoading.openLoading();
return next.handle(req).pipe(finalize(() => {
this._INotificationLoading.closeLoading();
}));
}
}
}
这是我的测试。
it('should be show loading', () => {
const next: any = {
handle: () => {
return Observable.create(subscriber => {
subscriber.complete();
});
}
};
const requestMock = new HttpRequest('GET', '/test');
const closeLoadingSpy = spyOn<INotificationLoading>(notification, 'closeLoading');
service.intercept(requestMock, next).subscribe(() => {
expect(closeLoadingSpy).toHaveBeenCalled();
});
expect(openLoadingSpy).toHaveBeenCalled();
});
简而言之,我通过传递一个Observable.create()作为方法句柄的返回来解决问题。在你的情况下,你可以将http mock的返回设置为一个Observable,并设置你需要检查测试的期望。
我有一个案例,我想确保从一个Observable的finalize块中调用 "移除加载指标 "方法。 这个服务是一个自制的服务,而不是HTTP,但它返回的是一个observable,所以希望你能适应它.我发现的关键是:1) 测试必须在一个假Async()块中运行.2)我必须在(模拟的)订阅上调用next.3)然后我必须在observable上调用complete()。
所以,我的解决方案基本上是这样的。
it ("should do something in finalize", () => {
let fakeResult = new Subject<any>();
// the "stop" method is called in the finalize of the Observable returned from testMethod()
spyOn(loadingService, "stop");
spyOn(service, "testMethod").andReturn(fakeResult);
component.methodUnderTestThatCallsServiceTestMethod(); // Observable returned here
fakeResult.next("whatever"); // Observable subscription fired here
tick();
fakeResult.complete(); // Observable finalize triggered here
expect(loadingService.stop).toHaveBeenCalled();
});