There are a lot of old answers that exist on this platform and I have tried them all, but none of them resolved my request.
Some methods were deprecated, and I found info that requires to use of NgModule
instead of SpyNgModuleFactoryLoader
. I also watched this video https://www.youtube.com/watch?v=PcwFcBsTAtM
But whatever I did, it didn't work. Has anyone tried testing lazy-loaded routes these days?
app-routing.module.spec.ts
import { Location } from '@angular/common';
import { NgModule } from '@angular/core';
import { ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { TestBed } from '@angular/core/testing';
import { Router, Routes } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { HomeModule } from './pages/home/home.module';
export const routes: Routes = [
{
path: 'home',
loadChildren: () => import('src/app/pages/home/home.module').then((m) => m.HomeModule),
},
{
path: 'sample',
loadChildren: () => import('src/app/pages/sample/sample.module').then((m) => m.SampleModule),
},
{ path: '', redirectTo: '/home', pathMatch: 'full' },
];
describe('Router: App', () => {
let location: Location;
let router: Router;
let fixture: ComponentFixture<AppComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes(routes)],
declarations: [AppComponent],
}).compileComponents();
router = TestBed.inject(Router);
location = TestBed.inject(Location);
fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
router.initialNavigation();
});
it('should navigate to files', fakeAsync(() => {
const loader = TestBed.inject(NgModule);
loader.stubbedModules = {
'./pages/home/home.module#HomeModule': HomeModule,
};
router.resetConfig([{ path: 'home', loadChildren: (): any => import('./pages/home/home.module').then((mod) => mod.HomeModule) }]);
router.navigateByUrl('/home');
tick(50);
fixture.detectChanges();
expect(location.path()).toBe('/home');
}));
});
This code gives me bellow error:
Chrome Headless 103.0.5060.114 (Mac OS 10.15.7) Router: App should navigate to files FAILED
NullInjectorError: R3InjectorError(CompilerModule)[DecoratorFactory -> DecoratorFactory]:
NullInjectorError: No provider for DecoratorFactory!
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'DecoratorFactory', 'DecoratorFactory' ] })
at NullInjector.get (http://localhost:9876/_karma_webpack_/vendor.js:49234:21)
I tried to test angular application with lazy loaded routing, but it is not worked