代码之家  ›  专栏  ›  技术社区  ›  James Barrett

如何将6+服务变量注入应用程序-路由.模块.规范.ts和测试路由器重定向

  •  2
  • James Barrett  · 技术社区  · 7 年前

    我试图测试一个用户是否被成功重定向,如果 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'.

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jan Wendland    7 年前

    在你的测试中,你要导航到主要路线( router.navigate([""]) router.navigate(['dashboard'])

    PS:Jasmine还附带了spies,它允许您通过指定服务方法的返回值来将组件测试与服务实现分离。不过,它们不能处理普通属性(没有getter/setter)。如果您的服务上有一个isAuthenticated方法,它将如下所示:

    const loginService = fixture.debugElement.injector.get(LoginService);
    spyOn(loginService, 'isAuthenticated').and.returnValue(true);
    

    间谍的作用域是每个IT块的,这意味着他们对你的其他测试没有任何副作用。

    推荐文章