mardi 14 janvier 2020

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?

Aucun commentaire:

Enregistrer un commentaire