【问题标题】:Mocking router.events.subscribe in Angular在 Angular 中模拟 router.events.subscribe
【发布时间】:2017-03-06 14:54:00
【问题描述】:

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

_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')

【问题讨论】:

    标签: unit-testing angular mocking jasmine


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 1970-01-01
      • 2023-04-07
      • 2013-12-22
      • 1970-01-01
      • 2020-02-14
      • 2018-06-08
      • 2019-06-12
      • 2021-12-21
      相关资源
      最近更新 更多