单元测试Angular 2 authGuard;间谍方法没有被调用

时间:2017-01-05 22:57:26

标签: unit-testing angular angular2-routing angular2-testing

我正在尝试对我的身份验证服务进行单元测试。从this answer我可以做到这一点,但现在当我为此进行单元测试时,它会显示Expected spy navigate to have been called

如何让我的间谍路由器在服务中用作this.router

AUTH-guard.service.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';

@Injectable()
export class AuthGuardService {

  constructor(private router:Router) { }

  public canActivate() {
    const authToken = localStorage.getItem('auth-token');
    const tokenExp = localStorage.getItem('auth-token-exp');
    const hasAuth = (authToken && tokenExp);

    if(hasAuth && Date.now() < +tokenExp){
      return true;
    }
    this.router.navigate(['/login']);
    return false;
  }
}

AUTH-guard.service.spec.ts

import { TestBed, async, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AuthGuardService } from './auth-guard.service';

describe('AuthGuardService', () => {
  let service:AuthGuardService = null;
  let router = {
    navigate: jasmine.createSpy('navigate')
  };

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        AuthGuardService,
        {provide:RouterTestingModule, useValue:router}
      ],
      imports: [RouterTestingModule]
    });
  });

  beforeEach(inject([AuthGuardService], (agService:AuthGuardService) => {
    service = agService;
  }));

  it('checks if a user is valid', () => {
    expect(service.canActivate()).toBeFalsy();
    expect(router.navigate).toHaveBeenCalled();
  });
});

RouterTestingModule替换为示例答案中的Router,会引发Unexpected value 'undefined' imported by the module 'DynamicTestModule'

2 个答案:

答案 0 :(得分:13)

不使用存根Router,而是使用依赖注入和间谍router.navigate()方法:

import { TestBed, async, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';

import { AuthGuardService } from './auth-guard.service';

describe('AuthGuardService', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AuthGuardService],
      imports: [RouterTestingModule]
    });
  });

  it('checks if a user is valid',

    // inject your guard service AND Router
    async(inject([AuthGuardService, Router], (auth, router) => {

      // add a spy
      spyOn(router, 'navigate');

      expect(auth.canActivate()).toBeFalsy();
      expect(router.navigate).toHaveBeenCalled();
    })
  ));
});

https://plnkr.co/edit/GNjeJSQJkoelIa9AqqPp?p=preview

答案 1 :(得分:2)

对于此测试,您可以使用ReflectiveInjector来解析和创建具有依赖关系的auth-gaurd服务对象。

但是,不是传递实际的路由器依赖性,而是提供具有导航功能的自己的Router类(RouterStub)。然后监视注入的Stub以检查是否调用了导航。

import {AuthGuardService} from './auth-guard.service';
import {ReflectiveInjector} from '@angular/core';
import {Router} from '@angular/router';

describe('AuthGuardService', () => {
    let service;
    let router;
    beforeEach(() => {
        let injector = ReflectiveInjector.resolveAndCreate([
            AuthGuardService,
            {provide: Router, useClass: RouterStub}
        ]);
        service = injector.get(AuthGuardService);
        router = injector.get(Router);
    });

    it('checks if a user is valid', () => {
        let spyNavigation = spyOn(router, 'navigate');
        expect(service.canActivate()).toBeFalsy();
        expect(spyNavigation).toHaveBeenCalled();
        expect(spyNavigation).toHaveBeenCalledWith(['/login']);
    });
});

class RouterStub {
        navigate(routes: string[]) {
             //do nothing
        }
}