How to unit test a component that depends on parameters from ActivatedRoute?

前端 未结 8 1106
离开以前
离开以前 2020-12-04 09:37

I am unit testing a component that is used to edit an object. The object has an unique id that is used in order to grab the specific object from an array of obj

相关标签:
8条回答
  • 2020-12-04 10:05

    Here is how I tested it in angular 2.0 latest...

    import { ActivatedRoute, Data } from '@angular/router';
    

    and in Providers section

    {
      provide: ActivatedRoute,
      useValue: {
        data: {
          subscribe: (fn: (value: Data) => void) => fn({
            yourData: 'yolo'
          })
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-04 10:15

    I have figured out how to do this!

    Since ActivatedRoute is a service, a mock service for it can be established. Let's call this mock service MockActivatedRoute. We will extend ActivatedRoute in MockActivatedRoute, as follows:

    class MockActivatedRoute extends ActivatedRoute {
        constructor() {
            super(null, null, null, null, null);
            this.params = Observable.of({id: "5"});
        }
    

    The line super(null, ....) initializes the super class, which has four mandatory parameters. However, in this instance, we need nothing from any of these parameters, so we initialize them to null values. All we need is the value of params which is an Observable<>. Therefore, with this.params, we override the value of params and initialize it to be the Observable<> of the parameter on which the test subject is relying.

    Then, as any other mock service, just initialize it and override the provider for the component.

    Good luck!

    0 讨论(0)
提交回复
热议问题