Unit test 'success' and 'error' observable response in component for Angular 2

核能气质少年 提交于 2019-12-06 10:46:48

I would create two mocks - one that throws an error:

class ObserverThrowServiceStub {
  getData() {
    return Observable.throw(new Error('Test error'));
  }
}

and one that returns successfully.

class ObserverSuccessServiceStub {
  getData() {
    return Observable.from(data);
  }
}

Then, instead of providing the same mock service to all tests, you provide the failing/successful mock service appropriately depending on the test in question (obviously you'll need to move your module configuration into a configurable method that you call from within each test rather than in the .beforeEach() code.

There is a really nice article on testing Angular services using Observables here (which uses exactly this model): http://www.zackarychapple.guru/angular2/2016/11/25/angular2-testing-services.html

someObj.ObservableReturninFunction().subscribe(
    (obj)=> {
        conosle.log(obj.message);
    },
    (err)=>{
        console.log(err.message);
    }
});
when success;
    SpyOn(someObj,"ObservableReturninFunction").and.returnValue(
            Observable.of({message: "something"}));
when erro:
    SpyOn(someObj,"ObservableReturninFunction").and.returnValue(
        Observable.throw({message: "some-error"}));

You can use Jasmine Spy to spyOn your mock service class's method which returns an Observable. More detail is here: Jasmine - how to spyOn instance methods

I would add a public error flag in the stub. Then I can create the stub once in beforeEach() and just update the error flag in each test case to decide which version of getData I want to use.

class ObserverServiceStub {
  public error = false;
  getData() {
    if (this.error) {
      return Observable.throw(new Error('Test error'));
    } else {
      return Observable.from(data);
    }
  }
}
install karma-firefox-launcher with
npm install karma-firefox-launcher --save-dev then



karma.config.js file  (the only part you will edit is this and leave other content)


plugins: [
      require('karma-jasmine'),
      require('karma-firefox-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
browsers: ['Firefox']    


input only firefox karma.config.js, chrome has issues currently
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!