Angular 2: Testing components with router

2019-02-22 03:12发布

I am writing the simplest component that is using a 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;
}

The problem occurs when I try testing this component. The moment I add the router link Karma is complaining about missing providers:

After adding all the providers Karma is asking I get this:

beforeEachProviders(() => [
    MemorySnippetComponent,
    MEMORY_SERVICE_PROVIDERS,
    ROUTER_PROVIDERS,
    ApplicationRef
]);

But when I run the test I get this error:

EXCEPTION: EXCEPTION: Error during instantiation of Token RouterPrimaryComponent! (RouterLink -> Router -> RouteRegistry -> Token RouterPrimaryComponent).

ORIGINAL EXCEPTION: unimplemented

ORIGINAL STACKTRACE: Error: unimplemented

What am I doing wrong??? Is Angular 2 (2.0.0-beta.1) just not ready for testing components with router directives?

2条回答
萌系小妹纸
2楼-- · 2019-02-22 03:38

For RC4 with new router now use ...

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

A github project using this approach is ...

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

查看更多
太酷不给撩
3楼-- · 2019-02-22 03:41

You should have a beforeEachProviders method looking like:

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

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

MockApplicationRef is provided by the framework for this kind of tests.

查看更多
登录 后发表回答