使用服务中的可观察性测试错误情况 [英] Testing error case with observables in services

查看:72
本文介绍了使用服务中的可观察性测试错误情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个订阅服务功能的组件:

Let's say I have a component that subscribes to a service function:

export class Component {

   ...

    ngOnInit() {
        this.service.doStuff().subscribe(
            (data: IData) => {
              doThings(data);
            },
            (error: Error) => console.error(error)
        );
    };
};

subscribe调用使用两个匿名函数作为参数,我设法建立了工作单元测试的数据功能,但因果报应不接受错误一的范围。

The subscribe call takes two anonymous functions as parameters, I've managed to set up a working unit test for the data function but Karma won't accept coverage for the error one.

我尝试在控制台上进行监视。错误函数,引发错误,然后期望间谍已被调用,但这并不能完全实现。

I've tried spying on the console.error function, throwing an error and then expecting the spy to have been called but that doesn't quite do it.

我的单元测试:

spyOn(console,'error').and.callThrough();

serviceStub = {
        doStuff: jasmine.createSpy('doStuff').and.returnValue(Observable.of(data)),
    };

    serviceStub.doStuff.and.returnValue(Observable.throw(

        'error!'
    ));

serviceStub.doStuff().subscribe(

    (res) => {

        *working test, can access res*
    },
    (error) => {

      console.error(error);
      console.log(error);  //Prints 'error!' so throw works.
      expect(console.error).toHaveBeenCalledWith('error!'); //Is true but won't be accepted for coverage.
    }
);

测试诸如此类的匿名函数的最佳实践是什么?确保测试覆盖率的最低要求是什么?

What's the best practice for testing anonymous functions such as these? What's the bare minimum to secure test coverage?

推荐答案

您可以简单地模拟Observable throw错误对象,例如 Observable .throw({status:404})并测试可观察到的错误块。

You can simply mock Observable throw error object like Observable.throw({status: 404})and test error block of observable.

const xService = fixture.debugElement.injector.get(SomeService);
const mockCall = spyOn(xService, 'method')
                       .and.returnValue(Observable.throw({status: 404}));

更新2019:

由于某些人懒洋洋地读评论,让我放在这里:
这是对Rxjs使用错误的最佳实践

Since some people are lazy to read comment let me put this here : It's a best practice to use errors for Rxjs

import { throwError } from 'rxjs'; // make sure to import the throwError from rxjs
const xService = fixture.debugElement.injector.get(SomeService);
const mockCall = spyOn(xService,'method').and.returnValue(throwError({status: 404}));

这篇关于使用服务中的可观察性测试错误情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆