dimanche 18 février 2018

angular2 test observable guard

I want to test a guard that returns observable response. Here is my guard code:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { UserService, User } from '@app/user';

@Injectable()
export class SignGuard implements CanActivate {
  constructor(private router: Router, private userService: UserService) { }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.userService.get().map((user: User) => {
      if (user.isPremium()) {
        this.router.navigate([state.url, 'success']);
        return false;
      } else {
        return true;
      }
    });
  }
}

And my test code

it('...', () => {
    const a = signGuard.canActivate(activatedSnapshot, mockSnapshot);
    console.log(a); // Observable
    a.subscribe(...); // Property 'subscribe' does not exist on type 'true'
})

Any ideas?

Aucun commentaire:

Enregistrer un commentaire