我试图测试一个用户是否被成功重定向,如果
authenticated
变量设置为true。
我试着把我的登录服务注入
beforeEach
设置
变量为false。然后,在单元测试中,将该变量设置为true。然后我希望我的警卫会发现
已验证
设置为true,然后重定向到仪表板页面。
应用程序路由-模块规范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");
});
}))
})
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;
}
}
}
登录.service.ts:
public authenticated = false;
export const routes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'dashboard', component: CurrentActivityComponent, canActivate: [LoginGuard] }
]
我希望测试能够通过,将用户重定向到“dashboard”,但失败的原因是:
Expected '/' to be '/dashboard'.