如何测试canActivate与角度2中的业力+茉莉?

时间:2017-02-02 08:15:31

标签: unit-testing angular testing karma-jasmine

Angular 2 v.2.0.0 - TS + karma + jasmine。

我会测试这个canActivate函数:

    public canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.serverThisLogin.checkAuth().map((e: boolean) => {
        if (e) {
            return true;
        }
    }). catch(() => {
        this.router.navigate(["/login"]);
        return Observable.of(false);
    });
}

如何实现这个?当我添加这个结构

    beforeEach(() => {
        canAct = new CanActivate(null, null);
    });

我收到此错误'CanActivate' only refers to a type, but is being used as a value here.

1 个答案:

答案 0 :(得分:2)

 import {Injectable} from "@angular/core";
 import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
 @Injectable()

    export class CanActivateInit implements CanActivate{
      constructor() {}
      canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if (/*somthing*/){
            return true;
        } else {
          return  true;
        }
      }
    }



import {CanActivateInit} from "./canActivateInit";
import {ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
export function main() {
  describe('CanActivateInit canActivate', () => {
    let canActivateInit : CanActivateInit;
    let next: ActivatedRouteSnapshot;
    let state: RouterStateSnapshot;

    beforeEach(() => {
      canActivateInit = new CanActivateInit();
    });

    it('should activate page' , () => {
      let result = canActivateInit.canActivate(next, state);
      expect(result).toBeTruthy();
    });

  });
}