2016-12-01 78 views
0

这里的服务:Angular 2/Jasmine/Karma错误:错误:无法解析路由器的所有参数:(?,?,?,?,?,?,?,?)。在配置/卡玛 - shim.js

import { Injectable } from '@angular/core'; 
 
import { Router, Event, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router'; 
 

 
@Injectable() 
 
export class LoaderService { 
 

 
    public shouldShowLoader: boolean = false; 
 

 
    constructor(private router: Router) { 
 
    router.events.subscribe((event: Event) => { 
 
     this.navigationInterceptor(event); 
 
    }); 
 
    } 
 

 
    // Shows and hides the loading spinner during Event changes 
 
    navigationInterceptor(event: Event): void { 
 
     if (event instanceof NavigationStart) { 
 
      this.shouldShowLoader = true; 
 
     } 
 
     else if (event instanceof NavigationEnd) { 
 
      this.shouldShowLoader = false; 
 
     } 
 

 
     // Set loading state to false in both of the below events to hide the spinner in case a request fails 
 
     else if (event instanceof NavigationCancel) { 
 
      this.shouldShowLoader = false; 
 
     } 
 
     else if (event instanceof NavigationError) { 
 
      this.shouldShowLoader = false; 
 
     } 
 
     else { 
 
      this.shouldShowLoader = false; 
 
     } 
 
    } 
 
}

这里是失败的试验:

import { TestBed, inject } from '@angular/core/testing'; 
 
import { Router } from '@angular/router'; 
 
import { LoaderService } from './loader.service'; 
 

 
describe('LoaderServiceTest',() => { 
 
    beforeEach(() => { 
 
     TestBed.configureTestingModule({ 
 
      providers: [ LoaderService, Router ] 
 
     }); 
 
    }); 
 
    
 
    it('#LoaderService should be defined', inject([LoaderService, Router], (service: LoaderService) => { 
 
     expect(service).toBeDefined(); 
 
    })); 
 

 
});

不确定它为什么失败?谷歌搜索类似的问题,我只能找到答案Angular 2测试版...我们正在使用最新的Angular 2/2.2.0

+0

什么是你得到的错误? –

回答

1

您的测试失败,因为您没有提供测试模块的所有参数路由器需要实例化。话虽如此,在单元测试中,不推荐使用像路由器这样的服务的实际实现。更好的选择是制作一个这样的存根(我在这里为路由器内部的一个函数添加了一个间谍来演示如果你想检查该函数是否在某个时刻被调用过将如何完成):

class RouterStub { 
    navigateByUrl = jasmine.createSpy('navigateByUrl'); 
} 

那么当您配置您的测试模块:

providers: [ 
    ..., 
    { provide: Router, useClass: RouterStub } 
] 

如果你想如何使用嘲笑和单元测试设置的更多信息,可以在官方文档在这里找到:https://angular.io/docs/ts/latest/guide/testing.html

相关问题