测试服务时如何模拟服务依赖关系?

时间:2019-07-31 10:44:31

标签: angular jestjs angular8 angular-test angular-testing

我必须测试使用其他服务的服务。 我创建了伪造的服务。 我将其配置为返回假值,并配置其他虚假服务以返回真值。 如何进行使用假冒服务的测试? 我需要一个测试才能使用第一个模拟,第二个测试才能使用第二个模拟。 但是在提供者数组中,我只能使用1个类 如何在第二个测试中将FakeVuiAuthServiceFalse用作依赖项?

/* 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();

      }));
});

1 个答案:

答案 0 :(得分:0)

您尝试像这样使用spyOn。

在单独的测试用例下指定spyOn并返回不同的值。

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