与Jasmine的Angular - 在测试函数中路由更改后未订阅路由参数

时间:2017-10-10 17:49:49

标签: angular unit-testing jasmine karma-runner

触发路由更改后,Location.path()告诉我它在新路由中,但ngOnInit(在组件中)无法订阅路由参数。

我的HTML:

<li>
  <a id="categoryButton{{category}}" 
     role="button" 
     style="color: white;background-color: #107C10;" 
     class="c-button f-primary" 
     [routerLink]="['/blog/category', category]">
     {{category}}
  </a>
</li>

我的测试功能:

it('when click on category link, route changes', async(inject([ Location], (location: Location) => {
    component.isLoading = false;
    const categoryTag = fixture.debugElement.query(By.css('#categoryButtonUpdates'));
    categoryTag.triggerEventHandler('click', { button: 0 } );
    fixture.detectChanges();
    fixture.whenStable().then(() => {
        expect(location.path()).toEqual('/blog/category/Updates');
        expect(component.route.params).toBeDefined();
        expect(component.category).toBe('Updates');
    });
})));
我的组件中的

ngOnInit()

ngOnInit() {
  this.testing = "works";
  this.getFeaturedBlogPost();
  this.route.params.subscribe(
     params => {
      this.category = params['category'];
      if (!this.category) {
        this.getBlogPost();
      } else {
        this.getBlogPostByCategory(this.category);
      }
  });
}

似乎component.category无法从params['category']获取类别值,因此它保持为undefined。我错过了什么?如何让组件识别参数更改?

0 个答案:

没有答案