这很重要,我该如何对该Guard进行单元测试,目的是如果我已通过身份验证,然后返回false并重定向到登录名,如果我们返回登录名,并且如果我们之前已进行身份验证,则转到个人资料如果这是我们第一次登录,请继续浏览页面,为什么?因为在这种情况下,我不想转到该路由(回调页面),所以从外部服务(okta)路由其回调,这是保护代码:
import { Injectable } from '@angular/core';
import { LoginMineService } from '../login/login-mine.service';
import { Router } from '@angular/router';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoginCheckGuard implements CanActivate {
constructor(private loginMineService: LoginMineService,
private router: Router,
) {
}
canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (!this.loginMineService.isAuthenticated) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
这是单元测试代码:
import { TestBed } from '@angular/core/testing';
import { LoginCheckGuard } from './login-check.guard';
describe('LoginCheckGuard', () => {
let guard: LoginCheckGuard;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(LoginCheckGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});
PS:我正在研究Angular 9,谢谢大家
类似这样的方法应该起作用:
import { TestBed } from '@angular/core/testing';
import { LoginCheckGuard } from './login-check.guard';
.......
describe('LoginCheckGuard', () => {
let guard: LoginCheckGuard;
let mockLoginMineService = { isAuthenticated: undefined };
let loginMineservice: LoginMineService;
let router: Router;
beforeEach(() => {
TestBed.configureTestingModule({
// RouterTestingModule to get a handle on the router in a testing environment
imports: [RouterTestingModule],
providers: [
LoginCheckGuard,
{ provide: LoginMineService, useValue: mockLoginMineService },
],
});
// get handle on items that are needed
guard = TestBed.inject(LoginCheckGuard);
loginMineService = TestBed.inject(LoginMineService);
router = TestBed.inject(router);
// spy on the router navigate
spyOn(router, 'navigate');
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
it('should return true if the user isAuthenticated', () => {
loginMineService.isAuthenticated = true;
expect(guard.canActivate()).toBe(true);
});
it('should return false if the user is not authenticated and navigate to login', () => {
loginMineService.isAuthenticated = false;
expect(guard.canActivate()).toBe(true);
expect(router.navigate).toHaveBeenCalledWith(['/login']);
});
});