我有一个名为OnlineReturn
的{{3}}组件,如下所示:
@Component({
selector: 'online-return',
templateUrl: 'views/OnlineReturnEligibility.html',
directives:[ReturnStarted],
providers: [craService]
})
使用此组件的类如下:
export class OnlineReturn implements OnInit{
constructor (private _cra : craService){}
//Fields and methods omitted.
submitClicked(){
let order = new Order();
order.emailId = this.email;
this._cra.postAggDetails(order, this.vendors, this.email).subscribe(
data => this.goodCra(data.json()),
err => this.badCra(err)
);
}
}
本质上,我订阅服务提供者中的一个方法,该方法接受一个observable并返回一个响应JSON对象。该服务如下所示:
@Injectable()
export class craService{
postAggDetails(order : Order, shipments: Array<Shipment>, email : string):Observable<any>{
let order_json = this.buildAggRequest(order, shipments);
if (this.hardcoded && email == "success@test.com"){
return this._http.get('./app/apiresponse/second_agg/SuccessResponse.json');
}
if (this.hardcoded && email == "failure@test.com"){
return this._http.get('./app/apiresponse/second_agg/ErrorResponse.json');
}
else {return this._http.get('./app/apiresponse/second_agg/SuccessResponse.json');}
}
我想使用Jasmine对组件中的submitClicked()方法进行单元测试。问题是,现在服务只是返回硬编码的响应,但最终一旦API端点在线,我将返回API的响应。
但我不确定这是否重要。最终,我想控制单元测试返回的JSON,并模拟不同的http响应代码以触发Angular中的成功或错误处理程序。我知道使用mockBackend来测试服务调用本身并返回Response对象,但是如何使用对服务的组件调用呢?也许我需要在组件中注入一个mockService?
我正在思考这个,但我的测试一直说订阅是未定义的。我在Jasmine中尝试了以下内容:
describe('Testing the service calls in the component', () =>{
beforeEachProviders(() => {
return [HTTP_PROVIDERS, provide(XHRBackend, {useClass: MockBackend}), OnlineReturn, craService];
});
it('should make successful call to the service when submit button clicked', inject([XHRBackend, ssrOnlineReturn, craService], (mockBackend, comp, serv) =>{
comp.email = "failure@hd.com";
comp.vendors.push(build_shipment());
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: secondAggFailure
}
)));
});
comp.submitClicked().subscribe((res) => {
expect(res).toEqual(secondAggFailure);
});
}));
});
非常感谢任何帮助!