在Angular中模拟router.events.subscribe

时间:2017-03-06 14:54:01

标签: unit-testing angular mocking jasmine

如何在路由器中模拟以下事件 -

_router.events.subscribe( event => {
        if ( event instanceof NavigationStart ) {
            this.authenticated = !!localStorage.getItem( 'accessToken' );
        }
    } );

我有以下模拟类 -

class MockRouter {
    public ne = new NavigationStart(0, 'http://localhost:4200/dashboard');
    public events = new Observable(observer => {
        observer.next(this.ne);
        observer.complete();
    });
}

这为我提供了以下错误 -

undefined is not an object (evaluating 'router.routerState.root')

1 个答案:

答案 0 :(得分:0)

我从angular.io docs -

找到了一个有用的存根
export class ActivatedRouteStub {

  // ActivatedRoute.params is Observable
  private subject = new BehaviorSubject(this.testParams);
  params = this.subject.asObservable();

  // Test parameters
  private _testParams: {};
  get testParams() { return this._testParams; }
  set testParams(params: {}) {
    this._testParams = params;
    this.subject.next(params);
  }

  // ActivatedRoute.snapshot.params
  get snapshot() {
    return { params: this.testParams };
  }
}