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
相关产品推荐
相关产品推荐

