mattsmith5
mattsmith5

Reputation: 1073

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

Upvotes: 1

Views: 2075

Answers (2)

Owen Kelvin
Owen Kelvin

Reputation: 15098

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;
  });
}

Upvotes: 1

AliF50
AliF50

Reputation: 18809

Are you able to do service = new AuthService()? It doesn't complain that it needs an argument?

Try doing:

service = new AuthService({/* mock ServiceAbcd here */});

Upvotes: 0

Related Questions