我必须测试一个使用其他服务的服务。我创造了伪造的服务。我将其配置为返回false值,并将其他伪服务配置为返回true值。如何进行使用假服务的测试?我需要一个测试来使用第一个mock,第二个测试来使用第二个mock。但是在提供者数组中,我只能使用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();
}));
});发布于 2019-07-31 19:02:20
您可以尝试像这样使用spyOn。
在seperate test case下指定spyOn并返回不同的值。
spyOn(AuthGuardService.prototype, 'isLoggedIn').and.callFake(() => { return true });https://stackoverflow.com/questions/57288957
复制相似问题