How to mock an activatedRoute parent Route in angular2 for testing purposes?

后端 未结 6 483
渐次进展
渐次进展 2020-12-05 03:57

Let\'s say I have this

export class QuestionnaireQuestionsComponent {

    questions: Question[] = [];
    private loading:boolean = true;


    constructor(         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 04:58

    For anyone new to this question the angular.io docs cover this scenario. See here

    As per documentation above:

    Create ActivatedRouteStub class to be used as test double for ActivatedRoute

    import { ReplaySubject } from 'rxjs/ReplaySubject';
    import { convertToParamMap, ParamMap, Params } from '@angular/router';
    
    /**
     * An ActivateRoute test double with a `paramMap` observable.
     * Use the `setParamMap()` method to add the next `paramMap` value.
     */
    export class ActivatedRouteStub {
      // Use a ReplaySubject to share previous values with subscribers
      // and pump new values into the `paramMap` observable
      private subject = new ReplaySubject();
    
      constructor(initialParams?: Params) {
        this.setParamMap(initialParams);
      }
    
      /** The mock paramMap observable */
      readonly paramMap = this.subject.asObservable();
    
      /** Set the paramMap observables's next value */
      setParamMap(params?: Params) {
        this.subject.next(convertToParamMap(params));
      };
    }
    

    And then use the stub in the test class as follows:

    activatedRoute.setParamMap({ id: '1234' });
    

提交回复
热议问题