Angular2 RC5 Mock Activated Route Params

后端 未结 2 1571
庸人自扰
庸人自扰 2020-12-16 00:46

I need to be able to mock the activated route parameters to be able to test my component.

Here\'s my best attempt so far, but it doesn\'t work.

{ pro         


        
2条回答
  •  青春惊慌失措
    2020-12-16 01:19

    Answer given by @jonrsharpe allows you to mock params, but those params would be the same in every test.

    If you want to be able to change the params, to set it at the start of a test, you can do it like this:

    At the top:

    describe('SomeComponent', () => {
      (...)
      let params: Subject;
      (...)
    

    in beforeEach (the async one - where you have imports, providers etc.):

    beforeEach(async(() => {
      params = new Subject();
      (...)
    

    in providers:

      (...)
      {
        provide: ActivatedRoute,
        useValue: {
          params: params
        }
      }
      (...)
    

    and then in test:

    it('someTest', () => {
      params.next({'id': '123'});
      fixture.detectChanges();
      (...)
    

    IMPORTANT NOTE

    Be sure to call fixture.detectChanges after params.next.

    This means you should remove fixture.detectChanges from beforeEach and add it to every test.

提交回复
热议问题