Mocking router.events.subscribe() Angular2

前端 未结 6 1182
生来不讨喜
生来不讨喜 2020-12-30 00:03

In my app.component.ts I have the following ngOnInit function:

ngOnInit() {
    this.sub = this.router.events.subscribe(e => {
      if (e instanceof Navi         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 00:49

    I created a version of the router stub from Angular docs that uses this method to implement NavigationEnd event for testing:

    import {Injectable} from '@angular/core';
    import { NavigationEnd } from '@angular/router';
    import {Subject} from "rxjs";
    
    @Injectable()
    export class RouterStub {
      public url;
      private subject = new Subject();
      public events = this.subject.asObservable();
    
      navigate(url: string) {
        this.url = url;
        this.triggerNavEvents(url);
      }
    
      triggerNavEvents(url) {
        let ne = new NavigationEnd(0, url, null);
        this.subject.next(ne);
      }
    }

提交回复
热议问题