Search code examples
angularunit-testingservicejasminekarma-runner

How to unit test function called in service's constructor?


How can I test, in the service's spec file, that a function is called in the constructor? For example:

@Injectable({
    providedIn: 'root'
})
export class myService {
  

    constructor() {
       this.myFunction();
    }

    myFunction(){}
}

So how can I test that my function was called?

beforeEach(() => {
TestBed.configureTestingModule({});
    service = TestBed.get(myService);

I can't spy on the service before the testbed.get, and I tried:

it('should demonstrate myFunction called in constructor', () => {
  const spy = spyOn (myService, 'myFunction');
  const serv = new myService();

  expect(spy).toHaveBeenCalled();
});

But this is failing to say spy wasn't called!

Any help would be most appreciated.


Solution

  • Use spyOn(obj, methodName) → {Spy} to spy the myFunction on MyService.prototype.

    E.g.

    service.ts:

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class MyService {
      constructor() {
        this.myFunction();
      }
    
      myFunction() {}
    }
    

    service.test.ts:

    import { MyService } from './service';
    
    describe('63819030', () => {
      it('should pass', () => {
        const myFunctionSpy = spyOn(MyService.prototype, 'myFunction').and.stub();
        const service = new MyService();
        expect(myFunctionSpy).toHaveBeenCalledTimes(1);
      });
    });