[英]how to mock service dependency when testing service?
我必須測試使用其他服務的服務。 我創建了偽造的服務。 我將其配置為返回假值,並配置其他虛假服務以返回真值。 如何進行使用假冒服務的測試? 我需要一個測試才能使用第一個模擬,第二個測試才能使用第二個模擬。 但是在提供程序數組中我只能使用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();
}));
});
您嘗試像這樣使用spyOn。
在單獨的測試用例下指定spyOn並返回不同的值。
spyOn(AuthGuardService.prototype, 'isLoggedIn').and.callFake(() => { return true });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.