Search code examples
angularhttprequestrxjsobservableangular2-testing

Unable to `subscribe` to `Observable` for http-get request in spec file


I want to test following service which return an 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;
        });
}

my spec file:

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

    }));

On debugging, the subscribe method is not executed. as a result my test case is getting pass without getting executed. what am i missing ?
P.S : MyService is not being used/called inside component at the moment.


Solution

  • finally i figured out the solution to it. Two changes I made:

    • using async() as pointed by @Gunter
    • stringify the response passed .

    here is the code :

    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
    
                    }); 
    
    })));