How to combine done callback with angular 2 unittest injection

I like the ability to pass a completed callback when unittest explicitly controls when unittest is considered complete. Can someone explain how this can be combined with dependency injection when using Angular 2?

Some more background:

A normal unittest with a callback function is as follows:

it('should work with done', (done: Function) => { setTimeout(() => { a.test(); }, 1000); a.test = () => { console.log('zweiter test'); expect(true).toBeFalsy(); done(); }; 

The Unittest created by the Angular 2 framework uses injection and looks like this:

  it('should be defined', inject([TxparserService], (service: TxparserService) => { expect(service).toBeTruthy(); })); 

I want to use both a callback function and dependency injection. What does it look like?

+5
source share
3 answers

Not sure if you can. Personally, however, I stopped using this style of injection for several reasons: 1. It is pretty verbose, and 2. You need to keep repeating it for each test case. A couple of other options:

  • Use beforeEach

     let service: TxparserService; beforeEach(() => { // configure }); beforeEach(inject([TxperserverService], (svc: TxparserService) => { service = svc; })); 
  • For me, beforeEach above still breaks my first concern about being verbose, so I'm just doing it like this now

     let service: TxparserService; beforeEach(() => { TestBed.configureTestingModule({ providers: [ TxparserService ] }); service = TestBed.get(TxparserService); }); 
+6
source

If you need to combine an inline asynchronous injection test, you can simply do the following:

 it('should work', (done) => inject([SomeService], (someService: SomeService) => { expect(true).toEqual(true); done(); })()); 

Make sure you immediately call the function returned by inject .

PS: Sometimes neither async nor fakeAsync works, and you still need it done in the old school ...

PPS: If anyone is interested in how to overcome problems with time-dependent Observable operations with jasmine-marbles , look at this short Example: marble-scheduler-injector.ts

+6
source

I was able to successfully combine fakeAsync with injection. So it will look like this:

 it('should be defined', fakeAsync(inject([TxparserService], (service: TxparserService) => { expect(service).toBeTruthy(); }))); 

Then you can combine it with the tick() function described in https://angular.io/guide/testing#the-fakeasync-function

+3
source

Source: https://habr.com/ru/post/1263827/


All Articles