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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With