Resolving Router parameters for Angular Unit Tests

March 13, 2019, 8:29 pm
Author: James Griffiths

Unit testing Angular applications can often throw up some unexpected surprises where dependencies are concerned.

The following error was one such instance:

'Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?)'

Fortunately resolving this particular error is fairly straightforward as we have 2 available solutions to choose from...

Solution #1 - Mocking the router

The first approach to fixing this issue is to simply create a mock class that simulates the Angular Router module and its methods.

This mock class can then be initialised within the providers array of Angular's configureTestingModule method.

All of this can be represented as shown in the following example unit test (note: realistically you would put your mocks into their own separate files for better management/organisation - but for the purposes of this article we'll proceed with all code in-situ):

import { TestBed, inject } from '@angular/core/testing';
import { Router } from '@angular/router';
import { PretendService } from './pretend-service.service';

class RouterMock {

  navigateByUrl(url: string) {
    return url;
  }

  serializeUrl(url: string) {
     return url;
  } 

  // Dummy further methods here if required
  
}

describe('PretendService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [PretendService,
                 {provide: Router, useClass: RouterMock}]
    });
  });

  it('should be created', inject([PretendService], (service: PretendService) => {
    expect(service).toBeTruthy();
  }));
});

Solution #2 - Use RouterTestingModule

Our second and final approach involves simply using Angular's default RouterTestingModule module (which, as the name implies, sets up the Angular Router for testing purposes) to overcome this error:

import { TestBed, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { PretendService } from './pretend-service.service';

describe('PretendService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      providers: [PretendService]
    });
  });

  it('should be created', inject([PretendService], (service: PretendService) => {
    expect(service).toBeTruthy();
  }));
});

Either of these methods can be used to overcome the 'Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?)' error with unit tests whose dependencies require use of the Angular Router class and its methods.

Categories

« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.