0

Technologies Used: Karma/Jasmine, Angular2

service.ts

Injectable()
export class Service { 

    constructor(private http: Http) { }
      getGoogle(): Observable<any>{
        console.log("Inside service");
        return this.http.get('https://jsonplaceholder.typicode.com/posts/1');    
     }}

Please ignore the Typos and all the imports are made correctly.API is getting called correctly in the UI.

service.spec.ts

describe('Provider:Service', () => {

const HERO_ONE = 'HeroNrOne';
const HERO_TWO = 'WillBeAlwaysTheSecond';

    let lastConnection;
    let service;


    beforeEach(() => {
        let injector = ReflectiveInjector.resolveAndCreate([
            { provide: ConnectionBackend, useClass: MockBackend },
            { provide: RequestOptions, useClass: BaseRequestOptions },
            Http,
            Service

        ]);
        service = injector.get(Service);
        let backend = injector.get(ConnectionBackend) as MockBackend;
        backend.connections.subscribe((connection: any) => lastConnection = connection);

    }); 

  it('getGoogle() should return the data in json format', fakeAsync(() => {
        console.log('1');
        let result:String[];
        service.getGoogle().toPromise().then((heroes:String[]) => result = heroes);
        lastConnection.mockRespond(new Response(new ResponseOptions({
            body:JSON.stringify({data: [HERO_ONE, HERO_TWO]}),
          })));
        tick();
        console.log(result[0]);
        console.log('3');

        expect(result.length).toEqual(2, 'should contain given amount of 
        heroes');   //this spec is failing because results does is not getting the response.  

    }));

The result:String[] is not getting the response that is provided.

Aditya
  • 2,358
  • 6
  • 35
  • 61
  • The test ends right after calling `getGoogle`. I believe the requests did not finish before the test did. Why do you unittest a call to external service? I think it should be mocked. – jacekbj Jul 29 '17 at 13:10
  • It means I have to make a mock response and pass it to the created mockbackend as a mockresponse? – Aditya Jul 29 '17 at 13:14
  • understood! Thanks – Aditya Jul 29 '17 at 13:22
  • @dzejdzej Can you solve it now? I have provided the mockresponse.But its not fetching it. – Aditya Jul 29 '17 at 14:18
  • I'm not an expert in testing (unluckily). I can see two ways of solving it: 1) Refactor your test to mimic Angular docs: https://angular.io/guide/http#testing-http-requests 2) Mock `XHRBackend` as done here: https://blog.thoughtram.io/angular/2016/11/28/testing-services-with-http-in-angular-2.html, which what I'm using (just slightly different from your implementation). I think the reason your solution doesn't work is because you're mocking an abstract class `ConnectionBackend`. – jacekbj Jul 29 '17 at 16:19

0 Answers0