Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test that Angular service have been initialized

I am trying to test my Angular service using Karma-Jasmine and I need to be sure that after service is initialized loadApp function have been called. What is the best way to test it?

import { Injectable, NgZone } from '@angular/core';

@Injectable()
export class GdlService {
  appName = 'myAppName';

  constructor(
    private ngZone: NgZone,
  ) {
    this.ngZone = ngZone;
    this.loadApp(this.appName);
  }


  private loadApp(appName) {
    this.ngZone.runOutsideAngular(() => {
      // ...some logic
    });
  }
}
like image 648
rel1x Avatar asked Dec 29 '17 12:12

rel1x


2 Answers

It can be tested as any other function. Considering that loadApp is prototype method, it can be stubbed or spied on class prototype:

it('', () => {
  spyOn(<any>GdlService.prototype, 'loadApp');
  const gdl = TestBed.get(GdlService);
  expect(gdl['loadApp']).toHaveBeenCalledWith('myAppName');
});
like image 67
Estus Flask Avatar answered Sep 20 '22 12:09

Estus Flask


Try mocking the injection for ngZone (I like ts-mockito for this sort of stuff) and then checking to see if ngZone.outsideOfAngular has been called. Due to the nature of typescript, I don't think you'll be able to directly spy on anything that is private comfortably.

Something like this in the test file:

import { GdlService } from 'place';
import { NgZone } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import {
    anything,
    instance,
    mock,
    verify
} from 'ts-mockito';

describe('yada yada', () => {
    const mockNgZone = mock(NgZone);
    // Can use when(mockNgZone.whatever)... to mock what you need
    beforeEach(() => {
        TestBed.configureTestModule({
            providers: [{
                provide: NgZone,
                useValue: instance(mockNgZone)
            }]
        });
    });

    it('checks on loadApp', () => {
        verify(mockNgZone.runOutsideAngular(anything())).called();
    });
});

If you would prefer to just use the spyOn method instead, you can just replace the object in the useValue portion of the provider.

like image 41
Ben Avatar answered Sep 19 '22 12:09

Ben