2

I am trying to write up a unit test for my service using MockBackend and each time I get a response as undefined. Any help would be appreciated. I have checked all these solutions below and compared to mine I really don't see much differences.

Here is my service:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { SomeObject } from './someObject';

@Injectable()
export class SomeService {

    private serviceUrl: string = 'http://localhost:8080/getObjects';  

    constructor( private http: Http ) { }

    getObjects() {
        return this.http.get( this.serviceUrl )
            .map(( response ) => response.json().content as SomeObject[])
    }
}

Here is my tests:

import { Http, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { TestBed, tick, fakeAsync, inject } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { SomeService } from './some.service';
import { SomeObject } from './someObject';

describe( 'SomeServiceTest', () => {

    let stubData: SomeObject[] = [
        new SomeObject( 1, "Title" )
    ];

    beforeEach(() => {
        TestBed.configureTestingModule( {
            providers: [
                SomeService,
                MockBackend,
                BaseRequestOptions,
                {
                    provide: Http,
                    useFactory: ( backend: MockBackend, options: BaseRequestOptions ) => {
                        return new Http( backend, options );
                    },
                    deps: [MockBackend, BaseRequestOptions]
                }
            ]
        });
    });

    it( 'should fetch data', inject( [SomeService, MockBackend], fakeAsync(( service: SomeService, mockBackend: MockBackend ) => {
        let res: SomeObject[];
        mockBackend.connections.subscribe( c => {
            expect( c.request.url ).toBe( 'http://localhost:8080/getObjects' );
            c.mockRespond( new Response( new ResponseOptions( {
                body: JSON.stringify( stubData )
            }) ) );
        });

        service.getObjects().subscribe(( response ) => {
            console.log( "response :: " + JSON.stringify( response ) ); // this is where I am seeing undefined
            res = response;
        });

        tick();

        expect( res[0].name ).toBe( 'Title' ); // this returns an exception TypeError: Cannot read property '0' of undefined
    }) ) );
});

1 Answer 1

4

I might be wrong, but I believe your issue is, first, that you are returning response.json().content as Object[] from your from your service.the content property is most likely undefined. I would suggest just mapping your response to a json object and having your component handle it.

getObjects() {
    return this.http.get( this.dealsUrl )
        .map(( response ) => response.json());
}

Then

service.getSomeObjectsUsingObservable().subscribe(( response ) => {
    console.log( "response :: " + JSON.stringify( response ) );
    if (response.content){
        res = response as SomeObject[];
    }
    else {
        //- fail test
    }
});
tick();
expect( res[0].name ).toBe( 'Title' );

Hope this helps

Sign up to request clarification or add additional context in comments.

3 Comments

Fixing the response from response.json().content as SomeObject[] to response.json() solved it. The second correction you suggested is not really the problem as you can see I have used fakeAsync in conjunction with tick() which handles my asynchronous calls. However, I still will accept this answer as the correct one.
Oh I see, I'll update my answer for future reference! Glad I was able to help.
Thanks a lot Daniel !! A second set of eyes always helps. I knew there was nothing wrong with the configuration and there is always a silly mistake behind these ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.