首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在测试服务时模拟服务依赖?

如何在测试服务时模拟服务依赖?
EN

Stack Overflow用户
提问于 2019-07-31 18:44:31
回答 1查看 88关注 0票数 0

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

代码语言:javascript
复制
/* 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();

      }));
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-31 19:02:20

您可以尝试像这样使用spyOn。

在seperate test case下指定spyOn并返回不同的值。

代码语言:javascript
复制
 spyOn(AuthGuardService.prototype, 'isLoggedIn').and.callFake(() => { return true });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57288957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档