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

Angular单元测试含Router依赖组件时出现No provider for Router错误

解决RouterTestingModule引入后仍报"No provider for Router"的问题

错误核心

错误提示NullInjectorError: No provider for Router!,根源是模板中的RouterLinkWithHref指令(通常来自<a routerLink>)无法获取Router实例。即便你已经引入RouterTestingModule,仍报错大概率是配置方式有误,或是模板中的子组件未正确处理。

解决方法

1. 确保RouterTestingModule调用withRoutes配置路由

RouterTestingModule必须通过withRoutes方法初始化路由配置,哪怕是空路由也不能省略,否则无法正确提供Router实例:

import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        // 必须调用withRoutes,传入空数组或测试用路由
        RouterTestingModule.withRoutes([])
      ],
      declarations: [AppComponent]
    }).compileComponents();
  });

  // 测试用例...
});

2. 处理模板中的子组件(如app-forgot-password)

从错误日志可见,你的AppComponent模板中包含<app-forgot-password>组件,如果这个子组件内部使用了routerLink,测试环境中需要做如下处理:

  • 方案一:声明子组件(若需测试子组件行为)
    import { ForgotPasswordComponent } from './forgot-password/forgot-password.component';
    
    // 在TestBed配置中添加子组件声明
    declarations: [AppComponent, ForgotPasswordComponent]
    
  • 方案二:使用NO_ERRORS_SCHEMA忽略未知组件(若无需测试子组件)
    import { NO_ERRORS_SCHEMA } from '@angular/core';
    
    // 在TestBed配置中添加schemas
    schemas: [NO_ERRORS_SCHEMA]
    

3. 验证测试床初始化流程

确保在beforeEach中正确完成TestBed配置,没有遗漏await或compileComponents(Angular 9+后可省略,但部分场景仍需保留)。

完整错误日志

NullInjectorError: StaticInjectorError(DynamicTestModule)[RouterLinkWithHref -> Router]: 
  StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
    NullInjectorError: No provider for Router!
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'RouterLinkWithHref', Function ], ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 33669121, rootNodeFlags: 33554433, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 33554433, childFlags: 114688, directChildFlags: 114688, childMatchedQueries: 0, matchedQueries: Object({  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 1, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: '', name: 'app-forgot-password', attrs: [  ], template: null, componentProvider: Object({ nodeIndex: 1, parent: <circular reference: Object>, renderParent: <circular reference: Object>, bindingIndex: 0, outputIndex: 0, checkIndex: 1, flags: 114688, childFlags: 0, directChildFlags: 0, childMatchedQueries: 0, matchedQueries: Object, matchedQueryIds: 0, references: Object,  ...
    at <Jasmine>
    at NullInjector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:855:1)
    at resolveToken (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:17514:1)
    at tryResolveToken (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:17440:1)
    at StaticInjector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:17266:1)
    at resolveToken (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:17514:1)
    at tryResolveToken (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:17440:1)
    at StaticInjector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:17266:1)
    at resolveNgModuleDep (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:30393:1)
    at NgModuleRef_.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:31578:1)
    at resolveDep (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:32143:1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:01:17