Search code examples
angulartypescriptkarma-jasmineangular11

Angular SpyOn Service with Another Parameter


How do I Spy on and Mock a Service with another service Parameter? Example, My New Authservice has this parameter,

export class AuthService{
    constructor(public serviceAbcd: ServiceAbcd) {}

This is an example resource, Without a constructor parameter on AuthService.

https://codecraft.tv/courses/angular/unit-testing/mocks-and-spies/

describe('Component: Login', () => {

  let component: LoginComponent;
  let service: AuthService;
  let spy: any;

  beforeEach(() => {
    service = new AuthService();
    component = new LoginComponent(service);
  });
    
  it('needsLogin returns true when the user has not been authenticated', () => {
    spy = spyOn(service, 'isAuthenticated').and.returnValue(false);
    expect(component.needsLogin()).toBeTruthy();
    expect(service.isAuthenticated).toHaveBeenCalled(); 
  });

  afterEach(() => { 
    service = null;
    component = null;
  });

});

We are trying to test without Testbed https://dev.to/angular/unit-testing-in-angular-to-testbed-or-not-to-testbed-3g3b


Solution

  • You can use angular's Testbed and inject the service

    import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
    
    describe('Component: Login', () => {
      let service: AuthService;
      beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
          imports: [
          ],
          declarations: [LoginComponent]
        })
          .compileComponents();
        service = Testbed.inject(AuthService);
      }));
      it('needsLogin returns true when the user has not been authenticated', () => {
        spy = spyOn(service, 'isAuthenticated').and.returnValue(false);
        expect(component.needsLogin()).toBeTruthy();
        expect(service.isAuthenticated).toHaveBeenCalled(); 
      });
    
      afterEach(() => { 
        service = null;
        component = null;
      });
    }