Angular 2:使用路由器测试组件

Tom*_*mog 7 angular2-routing angular

我正在编写使用routeLink的最简单的组件:

@Component({
    selector: 'memorySnippet',
    templateUrl: '<div class="memory-snippet-wrapper" *ngIf="memory" 
                  [routerLink]="['MainPanel', 'MemoryPanel', {'id' : this.memory.id}]">',
    directives: [CORE_DIRECTIVES, ROUTER_DIRECTIVES]
})
export class MemorySnippetComponent {
    @Input() memory: Memory;
}
Run Code Online (Sandbox Code Playgroud)

我尝试测试此组件时会出现此问题.我添加路由器链接Karma的那一刻抱怨缺少提供者:

添加所有提供商后,Karma要求我得到这个:

beforeEachProviders(() => [
    MemorySnippetComponent,
    MEMORY_SERVICE_PROVIDERS,
    ROUTER_PROVIDERS,
    ApplicationRef
]);
Run Code Online (Sandbox Code Playgroud)

但是当我运行测试时,我得到了这个错误:

EXCEPTION:EXCEPTION:Token RouterPrimaryComponent实例化时出错!(RouterLink - > Router - > RouteRegistry - > Token RouterPrimaryComponent).

原始例外:未实现

ORIGINAL STACKTRACE:错误:未实现

我究竟做错了什么???Angular 2(2.0.0-beta.1)还没准备好用路由器指令测试组件吗?

cex*_*yat 9

你应该有一个beforeEachProviders方法看起来像:

import {MockApplicationRef} from '@angular/core/testing';

beforeEachProviders(() => [
  ROUTER_PROVIDERS,
  provide(APP_BASE_HREF, {useValue: '/'}),
  provide(ROUTER_PRIMARY_COMPONENT, {useValue: YourComponent}),
  provide(ApplicationRef, {useClass: MockApplicationRef}
]);
Run Code Online (Sandbox Code Playgroud)

MockApplicationRef 由这种测试的框架提供.


dan*_*y74 5

对于带有新路由器的RC4现在使用...

beforeEach(() => addProviders([
  APP_ROUTER_PROVIDERS, // must be first
  {provide: APP_BASE_HREF, useValue: '/'}, // must be second
  {provide: ActivatedRoute, useClass: Mock},
  {provide: Router, useClass: Mock}
]));
Run Code Online (Sandbox Code Playgroud)

使用这种方法的github项目是......

https://github.com/danday74/angular2-coverage