You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular懒加载路由测试失败,求有效解决方案

Angular懒加载路由测试解决方案

错误原因分析

代码中TestBed.inject(NgModule)是完全错误的操作——NgModule是Angular的装饰器,并非可注入的服务,这直接触发了NullInjectorError。旧的SpyNgModuleFactoryLoader确实已被废弃,当前测试懒加载路由的正确方式是利用RouterTestingModule的原生能力,配合路由配置重置或直接提供模块引用。

修正后的测试代码

import { Location } from '@angular/common';
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';

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);
    
    // 初始化路由
    router.initialNavigation();
    fixture.detectChanges();
  });

  it('should navigate to home route successfully', fakeAsync(() => {
    // 重置路由配置,用已导入的HomeModule模拟懒加载
    router.resetConfig([
      {
        path: 'home',
        loadChildren: () => Promise.resolve(HomeModule)
      }
    ]);

    router.navigate(['/home']);
    tick(); // 等待异步路由导航完成
    fixture.detectChanges();

    expect(location.path()).toBe('/home');
  }));
});

关键修正点

  • 移除错误的NgModule注入操作,改用直接返回已导入模块的Promise来模拟懒加载行为。
  • 简化路由重置逻辑,删除无效的模块路径映射。
  • 移除tick()的延迟参数,默认tick()会等待所有异步操作完成,无需手动设置时间。

额外说明

若项目基于Angular 14+,还可以直接通过provideRoutes配置到TestBed.configureTestingModule的providers数组,或在RouterTestingModule.withRoutes中直接配置模拟懒加载的路由,无需手动重置路由配置。

内容的提问来源于stack exchange,提问作者Serkan KONAKCI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:16:14