Search code examples
angularunit-testingtestingroutertestbed

How to mock a Router object and inject into providers array in TestBed configuration


I'm trying to create and inject a mocked router object into TestBed configuration but it does not work. Below is the configuration :

let mockQuote: QuoteService = new QuoteService(null, null);
let mockOshcStore: OshcStore = new OshcStore(null);
let mockActivatedRoute: ActivatedRoute = new ActivatedRoute();
let mockRouter: Router = new Router(null, null, null, null, null, null, null, null);
//let mockRouter: RouterMock = new RouterMock();
//let router:Router;
TestBed.configureTestingModule({
  providers: [
    {
      provide: QuoteService, useFactory: () => {
        return mockQuote;
      }
    }, FormBuilder, AppStore,
    {
      provide: OshcStore, useFactory: () => {
        return mockOshcStore;
      }
    },
    {
      provide: ActivatedRoute, useFactory: () => {
        return mockActivatedRoute;
      }
    },
    {
      provide: Router, useFactory: () => {
        return mockRouter;
      }
    },
    HttpClient, QuoteCISLAdapter
  ],
  declarations: [CreateQuoteComponent]
});
fixture = TestBed.createComponent(CreateQuoteComponent);
component = fixture.componentInstance;

The above works until the 'ActivatedRoute' but stops when it hits the route and gives :

TypeError: Cannot read property 'get' of null

  at new Router (../packages/router/src/router.ts:406:30)

I also tried the imports array with 'RouterTestingModule' module as well but didn't work too. Any idea to craete a safe mocked Router object?


Solution

  • I usually have something like the above at the top of my beforeEach:

    mockActivatedRoute = {
                url: 'test',
                params: of({ paramOne: 1,paramTwo: 2018 })
            };
    

    and then the below in my providers array:

    { provide: ActivatedRoute, useValue: mockActivatedRoute },
    

    For route... this assumes you're only using navigate in your component if you're using more you'll need to mock more things:

    router = {
                navigate: jasmine.createSpy('navigate')
            };
    

    and then in the providers array:

    { provide: Router, useValue: router },