Search code examples
angularjestjsangular8angular-test

how to mock service dependency when testing service?


im have to test a service that uses other service. i created faked service. i configured it to return false value and other fake service to return true value. how can i make a test that uses the fake service? i need 1 test to use the first mock and the second test to use the second mock. but in the provider array i can use only 1 class how can i use the FakeVuiAuthServiceFalse in the second test as the dependency?

/* tslint:disable:no-unused-variable */

import { TestBed, async, inject } from '@angular/core/testing';
import { AuthGuardService } from './auth-guard.service';
import { VuiAuthService } from './vui-auth.service';
import { AUTH_REDIRECT } from './injection-tokens/injections-tokens';
import { RouterTestingModule } from '@angular/router/testing';
export class FakeVuiAuthServiceFalse {
  isLoggedIn(): boolean {
    return false;
  }
}
export class FakeVuiAuthServiceReturnTrue {
  isLoggedIn() {
    return true;
  }
}
describe('AuthGuard', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      providers: [AuthGuardService,

        {
          provide: AUTH_REDIRECT,
          useValue: {
            redirectTo: ''
          }
        },
        { provide: VuiAuthService, useClass: FakeVuiAuthServiceReturnTrue }
      ],
    });
  });


  it('when user  logged in should return true',
    inject([AuthGuardService, VuiAuthService],
      (service: AuthGuardService, dep: VuiAuthService) => {
        spyOn(dep, 'isLoggedIn');

        expect(service.canActivate).toBeTruthy();

      }));

  it('when user not logged in should return false',
    inject([AuthGuardService, VuiAuthService],
      (service: AuthGuardService, dep: VuiAuthService) => {
        spyOn(dep, 'isLoggedIn');
        expect(service.canActivate).toBeFalsy();

      }));
});

Solution

  • You try using spyOn like this.

    Specify spyOn under seperate test case and return different values.

     spyOn(AuthGuardService.prototype, 'isLoggedIn').and.callFake(() => { return true });