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

Angular与Jasmine测试:如何规避默认路由测试按钮点击后的指定路由

问题原因分析
  • 你没有给组件的view属性赋值,goToView方法中拼接路由时this.view是未定义状态,无法生成正确路由参数
  • router.navigate接收了两个参数:第一个是路由路径数组,第二个是携带relativeTo属性的配置对象,你的测试断言只匹配了第一个参数且值写错为['/dashboard'],和实际调用的参数不匹配
  • 组件依赖的ActivatedRoute(也就是你代码里的this.activeRoute)没有在测试模块中正确注入,相对路由的计算基准不存在
修复方案

方案1:轻量化单元测试(推荐,仅测试方法本身行为,不依赖路由真实能力)

直接mock组件依赖的Router和ActivatedRoute,不需要引入RouterTestingModule,测试逻辑更聚焦:

describe('HomeRedirectionBoxComponent', () => {
  let component: HomeRedirectionBoxComponent;
  let fixture: ComponentFixture<HomeRedirectionBoxComponent>;
  // 定义mock的router
  const mockRouter = jasmine.createSpyObj('Router', ['navigate']);
  // 定义mock的activatedRoute
  const mockActiveRoute = {} as ActivatedRoute;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [HomeRedirectionBoxComponent],
      // 直接提供mock的依赖,不需要引入RouterTestingModule
      providers: [
        { provide: Router, useValue: mockRouter },
        { provide: ActivatedRoute, useValue: mockActiveRoute }
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(HomeRedirectionBoxComponent);
    component = fixture.componentInstance;
    // 给view赋值为dashboard
    component.view = 'dashboard';
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should navigate to dashboard', () => {
    component.goToView();
    // 匹配navigate的两个参数即可
    expect(mockRouter.navigate).toHaveBeenCalledWith(
      ['../dashboard'], 
      { relativeTo: mockActiveRoute }
    );
  });
});

方案2:基于现有路由测试逻辑修改

如果你需要保留真实路由测试能力,修改现有测试用例即可:

it('should navigate to dashboard', fakeAsync(() => {
  // 先给view赋值
  component.view = 'dashboard';
  // 获取激活路由实例
  const activeRoute = TestBed.inject(ActivatedRoute);
  const navigateSpy = spyOn(router, 'navigate');
  
  component.goToView();
  
  // 正确匹配navigate的所有参数
  expect(navigateSpy).toHaveBeenCalledWith(
    ['../dashboard'],
    { relativeTo: activeRoute }
  );
}));

如果你需要验证最终跳转的路径确实是/dashboard,可以在调用goToView前先执行router.navigate(['/homePage']); tick();,把当前路由定位到首页,再通过expect(location.path()).toBe('/dashboard')验证跳转结果。

内容的提问来源于stack exchange,提问作者mr.Penguin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:24:06