【问题标题】:how to mock service dependency when testing service?测试服务时如何模拟服务依赖关系?
【发布时间】:2019-12-08 20:48:09
【问题描述】:

我必须测试使用其他服务的服务。 我创建了伪造的服务。 我将其配置为返回假值,其他假服务返回真值。 如何进行使用虚假服务的测试? 我需要一个测试来使用第一个模拟和第二个测试来使用第二个模拟。 但在提供者数组中,我只能使用 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();

      }));
});

【问题讨论】:

    标签: angular jestjs angular8 angular-test


    【解决方案1】:

    你尝试像这样使用 spyOn。

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

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

    【讨论】:

    • 它仅适用于 1 个测试,当我添加另一个测试时收到错误消息:[Function canActivate]
    • it('当用户登录时应该返回 true', inject([AuthGuardService, VuiAuthService], (service: AuthGuardService, dep: VuiAuthService) => { // spyOn(dep, 'isLoggedIn') ; spyOn(dep, 'isLoggedIn').and.returnValue(true); expect(service.canActivate).toBeTruthy(); }));
    • 这个测试正在运行,但是当我复制粘贴并将值更改为 false 时出现错误
    • 因为你已经使用了 stubbing 和 spyOn,所以默认情况下 Angular 会使用 stubbing。由于您在描述中使用了“FakeVuiAuthServiceReturnTrue”,因此即使您给出了不同的模拟,它每次都会调用“FakeVuiAuthServiceReturnTrue”。为避免使用存根,请删除此存根行“{ provide: VuiAuthService, useClass: FakeVuiAuthServiceReturnTrue }”并在每个测试用例下提供单独的 spyOn 定义。
    猜你喜欢
    • 2021-09-11
    • 2016-08-02
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多