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?
To run your tests using the Angular CLI, you use the ng test command in your terminal. As a result, Karma will open up the default browser and run all the tests written with the aid of Jasmine and will display the outcome of those tests.
router = TestBed. get(Router); Then, in the testcase, it('should show news intially ', () => { const navigateSpy = spyOn(router,'navigate'); component.
We can test routing in Angular by using RouterTestingModule instead of RouterModule to provide our routes. This uses a spy implementation of Location which doesn't trigger a request for a new URL but does let us know the target URL which we can use in our test specs.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With