如何测试canActivate
的angular函数,该函数返回的函数又返回boolean
的值?。
我尝试创建ActivatedrouterSnapshot
和routerStateSnapshot
的对象,并将其传递给canActivate
函数,但这无济于事。
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthenticationService,
private loginService: LoginService,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean>
| boolean {
return this.checkLogin(state.url);
}
checkLogin(url: string): boolean {
if (this.authService.isLoggedIn()) { return true; }
// Store the attempted URL for redirecting
this.loginService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
}
由于checklogin
返回true
,所以我希望这种情况发生。但是我不知道从哪里开始?。
答案 0 :(得分:1)
有很多方法可以做到这一点。我建议类似以下内容。只是为了显示某种多样性,我嘲笑了一个服务使用一个类,而另一个服务使用一个spyObject。
这是建议的代码:
class LoginMock implements Partial<LoginService> {
redirectUrl: string;
}
describe('AuthGuard', () => {
let authGuard: AuthGuard;
let loginService: LoginMock;
const routerMock = jasmine.createSpyObj('Router', ['navigate']);
const authMock = jasmine.createSpyObj('AuthenticationService', ['isLoggedIn']);
beforeEach(() => {
loginService = new LoginMock();
authGuard = new AuthGuard(authMock, loginService, routerMock);
});
it('should be createable', () => expect(authGuard).toBeTruthy());
it('should return true for canActivate() and not set loginService.redirectUrl when isLoggedIn === true', ()=> {
authMock.isLoggedIn.and.returnValue(true);
const result = authGuard.canActivate(new ActivatedRouteSnapshot(), <RouterStateSnapshot>{url: 'testUrl'});
expect(result).toBe(true);
expect(loginService.redirectUrl).toBeUndefined();
});
it('should return false for canActivate() and set loginService.redirectUrl when isLoggedIn === false', ()=> {
authMock.isLoggedIn.and.returnValue(false);
const result = authGuard.canActivate(new ActivatedRouteSnapshot(), <RouterStateSnapshot>{url: 'testUrl'});
expect(result).toBe(false);
expect(loginService.redirectUrl).toEqual('testUrl');
});
});
我已经为您准备了Stackblitz。随意将其派生到您自己的Stackblitz环境中并进行修改。
好运。 :)
答案 1 :(得分:1)
这个电晕天,我在办公室所能做的就是对某些应用程序进行单元测试。我做的最后一个测试是一个canActivate服务,它看起来像这样:
import {Injectable} from "@angular/core";
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from "@angular/router";
import {UserProvider} from "../core/app-initializers/user-provider.service";
import {permissionsList} from "../shared/models/permissions.model";
@Injectable()
export class CreateArrangementPermissionService implements CanActivate {
constructor(private router: Router, private userProvider: UserProvider) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if(route.params.idOrCreationKeyWord && route.params.idOrCreationKeyWord == 'create') {
if (this.userProvider.getConnectedUsersApplicativeRoles().indexOf(permissionsList.DECLARANT) < 0) {
this.router.navigate(['/forbidden']);
return false;
}
}
return true;
}
}
我已经编写了测试:
import { CreateArrangementPermissionService } from "./create-arr-permission-service";
import { TestBed, getTestBed } from "@angular/core/testing";
import { UserProvider } from "../core/app-initializers/user-provider.service";
import { Router } from "@angular/router";
describe('CreateArrangementPermissionService Unit tests', () => {
let injector: TestBed;
let userProvider = {
getConnectedUsersApplicativeRoles: function() {
return 'zorro'
}
};
let guard: CreateArrangementPermissionService;
let routeMock: any = {
snapshot: {},
params: {
idOrCreationKeyWord: 'create'
}
};
let routerStateMock: any = {
snapshot: {},
url: '/forbidden'
};
let routerMock = {
navigate: jasmine.createSpy('navigate')
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: UserProvider, useValue: userProvider},
{ provide: Router, useValue: routerMock },
AuthenticationErrorHandler,
AuthenticationErrorCommunicator,
CreateArrangementPermissionService,
]
});
injector = getTestBed();
userProvider = injector.get(UserProvider);
guard = injector.get(CreateArrangementPermissionService)
});
it('should redirect an unauthenticated user to forbidden', () => {
expect(guard.canActivate(routeMock, routerStateMock)).toEqual(false);
expect(routerMock.navigate).toHaveBeenCalledWith(['/forbidden'])
});
it('should allow the authenticated user to access app', () => {
let routeMockAdmin: any = {
snapshot: {},
params: {
idOrCreationKeyWord: 'TPRM_ADMINISTRATOR'
}
};
expect(guard.canActivate(routeMockAdmin, routerStateMock)).toEqual(true);
});
});
通过此测试,我在SonarQube上的覆盖率达到89.5%,缺少针对构造函数和“ indexOf()”的一些测试。 希望这个例子能帮助其他正确测试canActivate的人,然后再进行实验。