1

我想测试以下返回 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;
        });
}

我的规格文件:

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 方法。结果我的测试用例在没有被执行的情况下通过了。我错过了什么?
PS:MyService 目前没有在组件内部使用/调用。

4

2 回答 2

0

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

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

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

于 2016-06-02T10:55:08.410 回答
0

最后我想出了解决方案。我做了两个改变:

  • 使用async()@Gunter指出的
  • 对传递的响应进行字符串化。

这是代码:

fit('should get response',async(inject([XHRBackend, MyService], (mockBackend, service) => { //<--- wrap inside async call
    console.log("inside fit");
    let response = "something returned from service";
    let responseOptions = new ResponseOptions({ body: JSON.stringify(response) }); //<--- stringify the response

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

    service.getData('xyz').subscribe((a) => {
                    expect(a.length).toBe(11); //will fail
                   expect(a).toContain(“something”); //will pass

                }); 

})));
于 2016-06-06T13:04:19.620 回答