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

Angular12+中Update按钮点击测试报错:无法匹配路由

问题解决指南

1. 路由路径不匹配的核心修复

组件跳转路径与路由配置完全不一致,这是报错的根本原因:

  • productComponent.ts中,ADD按钮跳转用['AddProduct'],View/Update按钮跳转用['AddProduct', id]
  • 但App-Routing.module.ts里配置的路由是AddUpdateProduct和AddUpdateProduct/:id

修复方式:将组件内的跳转路径统一改为路由配置的名称:

// productComponent.ts 修改跳转代码
// ADD按钮跳转
this.router.navigate(['AddUpdateProduct']);
// View/Update按钮跳转
this.router.navigate(['AddUpdateProduct', id]);

2. Test2测试代码的错误修正

针对测试代码中的变量顺序、断言写法问题,给出具体调整方案:

  • 变量顺序问题:确保测试模块初始化(如导入RouterTestingModule)在获取组件实例之前完成,避免依赖未注入导致的错误
  • 断言写法错误:测试路由跳转时,需通过监听Router的navigate方法,断言其调用参数是否符合预期

示例修正后的Test2代码:

it('should navigate to AddUpdateProduct with id when View/Update button is clicked', () => {
  // 注入并监听路由服务
  const router = TestBed.inject(Router);
  const navigateSpy = spyOn(router, 'navigate');

  // 定位遍历生成的View/Update按钮(示例用class选择器,可根据实际调整)
  const updateButton = fixture.debugElement.query(By.css('.view-update-btn')).nativeElement;
  updateButton.click();
  fixture.detectChanges();

  // 断言跳转参数正确(替换为测试用的实际id)
  expect(navigateSpy).toHaveBeenCalledWith(['AddUpdateProduct', 1]);
});

额外注意事项

  • 测试模块配置时必须导入RouterTestingModule,避免路由测试依赖缺失
  • 遍历生成的按钮需添加可识别的标识(如class、data属性),确保测试时能精准定位目标元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:03:03