我正在按照本教程为我的功能身份验证防护编写单元测试,但是当我传递模拟身份验证服务以能够模拟 isLoggedIn() 时,我可以看到未模拟的服务仍在被使用茉莉花。这会导致它在 AuthService 中找到的依赖项上出错
auth.guard.ts:
export const authGuard = (data: any) => {
const authService = inject(AuthService);
if (authService.isLoggedIn()) { // test errors out here due to it still calling the unmocked isLoggedIn() function
return true;
}
if(data.parameters......){ // does some stuff with the data param
return true;
}
return false;
};
auth.guard.spec.ts:
let data = {
url: [
{
path: 'testpath',
parameters: {
src: 'testsrcparam',
},
},
],
};
const setup = (authServiceMock: unknown) => {
TestBed.configureTestingModule({
providers: [
authGuard,
{ provide: AuthService, useValue: authServiceMock }, // it should be using the mock service here
],
});
return TestBed.runInInjectionContext(() => authGuard(data));
};
it('should return true if user is authenticated', () => {
const mockAuthService: unknown = {
isLoggedIn: () => of(true),
};
const guard = setup(mockAuthService); // passing mock service to setup config
expect(guard).toBe(true);
});
据我所知,一切都已正确设置以利用模拟服务,但如果我将 console.log 放入 AuthService.isLoggedIn() 中,我可以看到单元测试仍然引用未模拟的函数。预先感谢您的帮助
嗯,我确实希望这会有所帮助,因为我确实用这样来测试我的 authguard。 正品,guard.spec.ts
import { TestBed, inject, getTestBed } from '@angular/core/testing';
import { AuthGuard } from './auth.guard';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';
import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('AuthGuard', () => {
let injector: TestBed;
let authService: AuthService
let guard: AuthGuard;
let routeMock: any = { snapshot: {}};
let routeStateMock: any = { snapshot: {}, url: '/cookies'};
let routerMock = {navigate: jasmine.createSpy('navigate')}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AuthGuard, { provide: Router, useValue: routerMock },],
imports: [HttpClientTestingModule]
});
injector = getTestBed();
authService = injector.get(AuthService);
guard = injector.get(AuthGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
it('should redirect an unauthenticated user to the login route', () => {
expect(guard.canActivate(routeMock, routeStateMock)).toEqual(false);
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
});
it('should allow the authenticated user to access app', () => {
spyOn(authService, 'isLoggedIn').and.returnValue(true);
expect(guard.canActivate(routeMock, routeStateMock)).toEqual(true);
});
});