我正在尝试测试是否将authenticated
变量设置为true时是否成功重定向了用户。
我尝试将LoginService注入beforeEach
并将authenticated
变量设置为false。然后,在单元测试中,将该变量设置为true。然后,我希望我的警卫了解authenticated
设置为true的事实,然后重定向到仪表板页面。
app-routing-module.spec.ts:
import { LoginService } from './services/login.service';
import { Router } from "@angular/router";
import { RouterTestingModule } from '@angular/router/testing';
import { Location } from "@angular/common";
import { routes } from "./app-routing.module";
import { AppComponent } from './components/app.component';
describe('AppRoutingModule, () => {
let location: Location;
let router: Router;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [LoginService]
})
router = TestBed.get(Router);
location = TestBed.get(Location);
fixture = TestBed.createComponent(AppComponent);
router.initialNavigation();
});
beforeEach(inject([LoginService], (loginService: LoginService) => {
loginService.authenticated = false;
}))
it('should redirect the user form the LoginComponent to the DashboardComponent if the user is already logged in', inject([LoginService](loginService: LoginService) => {
loginService.authenticated = true;
console.log(loginService);
router.navigate([""]).then(() => {
expect(location.path()).toBe("/dashboard");
});
}))
})
login.guard.ts:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { LoginService } from '../services/login.service';
import { Observable } from 'rxjs/index';
@Injectable({
providedIn: 'root'
})
export class LoginGuard implements CanActivate {
constructor(private router: Router, private loginService: LoginService) {
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
console.log('checked authenticated guard');
if (this.loginService.authenticated === true) {
this.loginService.navigationState.next(true);
return true;
} else {
this.router.navigate(['']);
return false;
}
}
}
login.service.ts:
public authenticated = false;
app-routing.module.ts:
export const routes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'dashboard', component: CurrentActivityComponent, canActivate: [LoginGuard] }
]
我希望测试通过,将用户重定向到“仪表板”,但是失败,并显示:Expected '/' to be '/dashboard'.
我怀疑这与我注入服务的方式有关。但是我不确定自己在做什么错。
答案 0 :(得分:0)
在您的测试中,您导航到根本没有保护的主路由(router.navigate([""])
)(换句话说,没有呼叫您的保护)。仅当您实际上尝试访问受保护的路由时,才会调用该保护。因此,在测试中,您必须导航至仪表板(router.navigate(['dashboard'])
)才能通过。
要实现您描述的重定向行为,您必须为此目的在第一条路由上添加另一个防护。
PS:茉莉花还带有间谍,可以让您f.i.通过指定服务方法的返回值,使组件测试与服务实现脱钩。但是,它们不能用于普通属性(没有getter / setter)。如果您的服务上有一个isAuthenticated方法,则它看起来像这样:
const loginService = fixture.debugElement.injector.get(LoginService);
spyOn(loginService, 'isAuthenticated').and.returnValue(true);
间谍按IT块划分范围,这意味着它们对您的其他测试没有任何副作用。