【问题标题】:Angular 2 testing Router with Jasmine and KarmaAngular 2 使用 Jasmine 和 Karma 测试路由器
【发布时间】:2016-10-07 21:48:21
【问题描述】:

我在为 Angular 2 中的 router.navigate 编写存根时遇到问题。我目前编写了以下存根。这是角度文档中显示的内容。

@Injectable
export class RouterStub {
    navigate(commands: any[], extras?: NavigationExtras) { }

但是,当我使用此存根时,我收到以下错误。

TypeError: this.router.navigate is not a function 

我的导航用法如下。

let summaryLink = ['/summary', this.client.id, this.client.lastName];
this.router.navigate(summaryLink);

任何帮助将不胜感激。

只是一个更新...我能够使用我发现引用 here 的非 TestBed 方法进行此测试。但是,如果有人能够弄清楚如何使用 TestBed 方法进行此测试,我将不胜感激。 谢谢

【问题讨论】:

    标签: angular jasmine karma-runner angular2-testing angular2-router


    【解决方案1】:

    您必须引导您的测试,包括路由器模块。这与引导应用程序非常相似:

    const IMPORTS: any[] = [
        BrowserModule,
        ...
        RouterModule.forRoot(routes)
    ];
    
    beforeEach(async(() => {
      TestBed.configureTestingModule({
        imports: IMPORTS,
        declarations: DECLARATIONS
        providers: PROVIDERS
      }).compileComponents();
    }));
    

    然后,就可以获取到路由器的引用了。

     beforeEach(() => {
      router = TestBed.get(Router);
      fixture = TestBed.createComponent(YourComponent);
      component = fixture.componentInstance;
      element = fixture.nativeElement;
    });
    

    测试状态(需要依赖,因为组件被渲染等等):

    it('routes to the dummy component', fakeAsync(() => {
      tick(1000);
      fixture.detectChanges();
    
      router.navigate(['dummy']);
    
      tick(1000);
      fixture.detectChanges();
    
      expect(router.isActive('/dummy', true)).toBe(true);
    }));
    

    测试通信(不路由;我们只需要验证导航是否真的发生):

    it('routes to the dummy component', fakeAsync(() => {
      spyOn(router, 'navigate').and.callFake(() => {});
      tick(1000);
      fixture.detectChanges();
    
      router.navigate(['dummy']);
    
      tick(1000);
      fixture.detectChanges();
    
      expect(router.navigate).toHaveBeenCalledWith(['dummy']);
    }));
    

    在实际测试中,您不会测试 navigate() 方法。实际上,您将要测试某种用户行为,例如点击:

    在组件中(在本例中为 YourComponent):

    onClick() {
        this.router.navigate(['dummy']);
    }
    

    在测试中(将 navigate() 替换为点击触发器):

    element.querySelector('button').click();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 2017-05-01
      • 2015-12-07
      • 1970-01-01
      • 2018-12-05
      • 2017-02-24
      • 2018-01-31
      相关资源
      最近更新 更多