简体   繁体   中英

Angular 2: Testing components with router

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM