user1781710
user1781710

Reputation:

Angular 2 / Jasmine / Karma error: Error: Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?, ?). in config/karma-shim.js

Here is the service:

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;
        }
    }
}

Here is the test that is failing:

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();
    }));

});

Not sure why it's failing? Googling for similar issues, I can only find answers for Angular 2 beta... we are using the latest Angular 2 / 2.2.0

Upvotes: 0

Views: 2118

Answers (1)

peppermcknight
peppermcknight

Reputation: 1555

Your test is failing because you have not provided the testing module with all the parameters that the Router needs to be instantiated. Having said that, in a unit test it is not recommended to use the actual implementation of a service like the Router. A better alternative would be to make a stub like this (I've added a spy for a function inside the router here to demonstrate how it would be done if you wanted to check that the function had been called at some point):

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

then when you are configuring your testing module:

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

If you want further information on how to use mocks and unit testing setup it can be found in the official docs here: https://angular.io/docs/ts/latest/guide/testing.html

Upvotes: 0

Related Questions