简体   繁体   English

在Angular中模拟router.events.subscribe

[英]Mocking router.events.subscribe in Angular

How would I go about mocking an event in router for the following - 我将如何在路由器中模拟以下事件 -

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

I have the following mock class - 我有以下模拟类 -

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

This provides me with the following error - 这给我提供了以下错误 -

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

I found a useful stub from the angular.io docs - 我从angular.io 文档中找到了一个有用的存根 -

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 };
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM