Search code examples
angularunit-testingangular-router

Angular test NavigationError event handler


I have a method that handles chunk load error and shows a notification. The problem is that I cannot mock NavigationError which I need in order to pass filter condition filter((e) => e instanceof NavigationError && e.error.name === 'ChunkLoadError').

However, I cannot create this error on my own. When I create my instance of NavigationError I get error that

Error: ASSERTION ERROR: NgModule 'NavigationError(id: 1, url: '1', error: 1)' is not a subtype of 'NgModuleType'. [Expected=> null != null <=Actual]

RouterTestingModule.withRoutes([
{
   path: 'loadErr',
   loadChildren: () =>Promise.resolve(new NavigationError(1, '1', 1)),
},
]),

How do I create an instace of this error?


Solution

  • It appears that you don't need to create NavigationError explicitly. You can reject the promise what will automatically cause NavigationError.

    Now the route setup looks like this

    RouterTestingModule.withRoutes([
      {
        path: 'loadErr',
        loadChildren: () =>
          Promise.reject({name: 'ChunkLoadError'}),
      },
    ]),
    

    And the test itself

    ngZone
      .run(() => router.navigateByUrl('loadErr'))
      .then(() => done.fail('Eror expected'))
      .catch(() => expect(notificationService.showError).toHaveBeenCalled());
    
      tick(100);