无法为spec文件中的http-get请求“订阅”`Observable`

时间:2016-06-02 10:52:06

标签: angular httprequest rxjs observable angular2-testing

我想测试以下服务,该服务返回一个observable:

 public getData(str:string) {
    // return an observable
    return this.http.get(‘calltoserviceapi’+str)
        .map( (responseData) => {

            return responseData.json().Abc;
        })
        .map((s: Array<any>) => {
            let result:Array<AbcModel> = [];
            if (s) {
                s.forEach((s) => {
                    result.push(
                        new AbcModel(s.Val1,
                            s.Val2,
                            ));
                });
            }
            return result;
        });
}

我的spec文件:

fdescribe ("my-service.spec.js", ()=> {

    beforeEachProviders(() => [
        MyService,
        BaseRequestOptions,
        MockBackend,
        provide(Http, {
            useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
                return new Http(backend, defaultOptions);
            },
            deps: [MockBackend, BaseRequestOptions]
        }),
        provide(XHRBackend, {useClass: MockBackend})
    ]);



fit('should get response',inject([XHRBackend, MyService], (mockBackend, service) => {
        console.log("inside fit");
        let response = "something returned from service";
        let responseOptions = new ResponseOptions({ body: response });

        mockBackend.connections.subscribe((connection: MockConnection) => {
                connection.mockRespond(new Response(responseOptions));
        });

        service.getData('xyz').subscribe((a: MyModel[]) => {
                    expect(a.length).toBe(11); //this is NOT failing
              expect(a).toContain(“something”);

                }); //debugger not going inside subscribe

    }));

在调试时,不执行subscribe方法。结果我的测试用例没有被执行就通过了。我错过了什么?     P.S:MyService目前尚未在组件内使用/调用。

2 个答案:

答案 0 :(得分:0)

我认为您需要添加async(...)

fit('should get response',async(inject([XHRBackend, MyService], (mockBackend, service) => {

使测试等到所有异步任务完成。否则,http.get()任务将被安排,然后测试结束。

答案 1 :(得分:0)

最后我找到了解决方案。我做了两个改变:

  • 使用@Gunter
  • 指出的imageView.setImageResource(R.drawable.your_icon_name);
  • 字符串化传递的响应。

这是代码:

async()