Модульное тестирование Angular 2 authGuard; шпионский метод не вызывается

Я пытаюсь провести модульное тестирование службы защиты авторизации. Из этот ответ я смог зайти так далеко, но теперь, когда я запускаю модульный тест для этого, он говорит Expected spy navigate to have been called.

Как сделать так, чтобы мой шпионский маршрутизатор использовался как this.router в сервисе?

авторизация-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;
  }
}

авторизация-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'.


person coblr    schedule 05.01.2017    source источник
comment
RouterTestingModule — это модуль, а не провайдер. Если он определяется как провайдер, ничего не происходит.   -  person Estus Flask    schedule 06.01.2017


Ответы (2)


Вместо заглушки 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

person stealththeninja    schedule 06.01.2017
comment
Именно то, что я искал! Простое решение. Большое спасибо, милостивый государь! - person coblr; 06.01.2017
comment
Это намного лучше, чем другие примеры охранников, которые я нашел @stealththeninja, спасибо! - person Shawn; 20.06.2017

Для этого теста вы можете использовать ReflectiveInjector для разрешения и создания объекта службы auth-gaurd с зависимостями.

Но вместо того, чтобы передавать фактическую зависимость Router, предоставьте свой собственный класс Router (RouterStub), который имеет функцию навигации. Затем проследите за введенной заглушкой, чтобы проверить, была ли вызвана навигация.

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
        }
}
person qdivision    schedule 06.01.2017