Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Angular 2 service that returns a Promise

I'm trying to unit test a service which should use fake http backend, provided by Angular's in-memory data service. This is the relevant code:

describe('getCars() method ', ()  => {
      it('should return a resolved Promise', inject([DataService], (service: DataService) => {
        service.getCars().then((value) => {
          expect(value.length).toBe(3);
       });
    }));
  });

The problem is I can't use Jasmine's done callback to treat the asynchronous service.getCars() call, because of how inject function works. I can't use async test helper neither, because it can't work with promises. So I have no idea how to wait for promise to resolve---the test just runs without ever reaching expect.

like image 606
Dalibor Dragojevic Avatar asked Nov 30 '16 10:11

Dalibor Dragojevic


1 Answers

Use async, which will wrap it a zone, waiting for all asynchronous tasks to complete before the test completes.

import { async } from '@angular/core/testing';

                                   // !!!!!!!
it('should return a resolved Promise', async(inject([DataService], (service: DataService)=>{
  service.getCars().then((value) => {
    expect(value.length).toBe(3);
  });
})));

Also another option is to not use inject at all. You can just get services from the TestBed. It's a lot clearer

let service: DataService;

beforeEach(() => {
  const injector = TestBed.configureTestingModule({});
  service = injector.get(DataService);
});

No need for inject, and it's a lot less verbose. You can now use done. Or if you want, still do it the Angular way, and use async.

See also:

  • Docs testing section on async
like image 75
Paul Samsotha Avatar answered Nov 15 '22 06:11

Paul Samsotha