如何对调用可观察服务的组件进行单元测试 [英] How to unit test a component that calls observable service
本文介绍了如何对调用可观察服务的组件进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对已订阅可观察服务的功能进行单元测试.不知道从哪里开始.
I am trying to unit test a function that is subscribed to an observable service. Not sure where to start.
我要进行单元测试的组件功能:
Component function I am trying to unit test:
register() {
this._registrationService.registerUser(this.form.value)
.subscribe(data => {
if (data) {
this.errorMessage = '';
this.successMessage = 'Account successfully created';
} else {
this.errorMessage = 'Error';
this.successMessage = '';
}
},
error => {
this.errorMessage = error;
this.successMessage = '';
});
}
服务:
registerUser(user) {
const registerUrl = this.apiUrl;
return this._http.post(registerUrl, JSON.stringify(user), { headers: this.apiHeaders })
.map(res => res.json())
.catch(this._handleError);
}
推荐答案
我将模拟RegistrationService
服务以使用Observable.of
返回数据.
I would mock the RegistrationService
service to return data using Observable.of
.
class MockRegistrationService {
registerUser(data: any) {
return Observable.of({});
}
}
在单元测试中,您需要通过模拟的服务覆盖RegistrationService
服务:
Within you unit test, you need to override the RegistrationService
service by the mocked one:
describe('component tests', () => {
setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS,
TEST_BROWSER_APPLICATION_PROVIDERS);
var service = new MockRegistrationService();
beforeEachProviders(() => [
provide(RegistrationService, { useValue: service })
]);
it('should open',
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb
.createAsync(RegistrationComponent)
.then(fixture => {
let elt = fixture.nativeElement;
let comp: RegistrationComponent = fixture.componentInstance;
fixture.detectChanges();
expect(comp.successMessage).toEqual('Account successfully created');
expect(comp.errorMessage).toEqual('');
});
});
}));
});
有关更多详细信息,请参见此plunkr: https://plnkr.co/edit/zTy3Ou?p = info .
See this plunkr for more details: https://plnkr.co/edit/zTy3Ou?p=info.
这篇关于如何对调用可观察服务的组件进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文