编写 Karma-Jasmine 单元测试用例时出现“错误:没有路由器提供程序”

     2023-02-26     120

关键词:

【中文标题】编写 Karma-Jasmine 单元测试用例时出现“错误:没有路由器提供程序”【英文标题】:"Error: No provider for router" while writing Karma-Jasmine unit test cases 【发布时间】:2017-04-22 11:51:04 【问题描述】:

我们已经完成了一个 angular2 项目设置,并在其中创建了一个模块(my-module),并在该模块中使用以下 cmd 命令创建了一个组件(my-new-component):

ng new angular2test
cd angular2test
ng g module my-module
ng generate component my-new-component

创建设置和所有组件后,我们从 angular2test 文件夹中的 cmd 运行 ng test 命令。

以下文件是我们的 my-new-component.component.ts 文件

import  Component, OnInit  from '@angular/core';
import  Router, Routes, RouterModule  from '@angular/router';
import  DummyService  from '../services/dummy.service';

@Component(
  selector: 'app-my-new-component',
  templateUrl: './my-new-component.component.html',
  styleUrls: ['./my-new-component.component.css']
)
export class MyNewComponentComponent implements OnInit 

  constructor(private router : Router, private dummyService:DummyService)  

  ngOnInit() 
  
    redirect() : void
        //this.router.navigate(['/my-module/my-new-component-1'])
    

以下文件是我们的 my-new-component.component.spec.ts 文件

/* tslint:disable:no-unused-variable */
import  async, ComponentFixture, TestBed  from '@angular/core/testing';
import  By  from '@angular/platform-browser';
import  DebugElement  from '@angular/core';

import  RouterTestingModule  from '@angular/router/testing';
import NgbModule from '@ng-bootstrap/ng-bootstrap';
import  DummyService  from '../services/dummy.service';

import  MyNewComponentComponent  from './my-new-component.component';

describe('MyNewComponentComponent', () => 
  let component: MyNewComponentComponent;
  let fixture: ComponentFixture<MyNewComponentComponent>;

  beforeEach(async(() => 
    TestBed.configureTestingModule(
        imports: [RouterTestingModule, NgbModule.forRoot(), DummyService],
      declarations: [ MyNewComponentComponent ]
    )
    .compileComponents();
  ));

  beforeEach(() => 
    fixture = TestBed.createComponent(MyNewComponentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  );

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

我们在运行 ng test 命令时遇到以下 cmd 错误:

    Chrome 54.0.2840 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.593 secs / 2.007 secs)
Chrome 54.0.2840 (Windows 7 0.0.0) MyNewComponentComponent should create FAILED
        Failed: Unexpected value 'DummyService' imported by the module 'DynamicTestModule'
        Error: Unexpected value 'DummyService' imported by the module 'DynamicTestModule'

我们更新了组件文件和规范文件。很高兴找到下面的代码 sn-p。

以下文件是我们的 my-new-component.component.ts 文件

import  Component, OnInit  from '@angular/core';
import  Router, Routes, RouterModule  from '@angular/router';
import  DummyService  from '../services/dummy.service';

@Component(
  selector: 'app-my-new-component',
  templateUrl: './my-new-component.component.html',
  styleUrls: ['./my-new-component.component.css']
)
export class MyNewComponentComponent implements OnInit 

  constructor(private router : Router, private dummyService:DummyService, public fb: FormBuilder)  
  super(fb);
  

  ngOnInit() 
  
    redirect() : void
        //this.router.navigate(['/my-module/my-new-component-1'])
    

以下文件是我们的 my-new-component.component.spec.ts 文件

/* tslint:disable:no-unused-variable */
import  async, ComponentFixture, TestBed  from '@angular/core/testing';
import  By  from '@angular/platform-browser';
import  DebugElement  from '@angular/core';
import  FormsModule, FormGroup, FormBuilder, Validators, ReactiveFormsModule from '@angular/forms';
import  SplitPipe  from '../../common/pipes/string-split.pipe';
import  RouterTestingModule  from '@angular/router/testing';
import  DummyService  from '../services/dummy.service';
import  MyNewComponentComponent  from './my-new-component.component';

describe('MyNewComponentComponent', () => 
  let component: MyNewComponentComponent;
  let fixture: ComponentFixture<MyNewComponentComponent>;

  beforeEach(async(() => 
    TestBed.configureTestingModule(
        imports: [RouterTestingModule, DummyService ,HttpModule, FormBuilder],
      declarations: [ MyNewComponentComponent, SplitPipe]
    )
    .compileComponents();
  ));

  beforeEach(() => 
    fixture = TestBed.createComponent(MyNewComponentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  );

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

但是在运行 ng test 命令时,我们得到了以下错误。

09 12 2016 09:13:48.987:WARN [karma]: No captured browser, open http://localhost:9876/
09 12 2016 09:13:49.008:INFO [karma]: Karma v1.2.0 server started at http://localhost:9876/
09 12 2016 09:13:49.010:INFO [launcher]: Launching browser Chrome with unlimited concurrency
09 12 2016 09:13:49.420:INFO [launcher]: Starting browser Chrome
09 12 2016 09:13:58.642:INFO [Chrome 54.0.2840 (Windows 7 0.0.0)]: Connected on socket /#QZ9LSSUVeK6KwNDlAAAA with id 46830907
        Failed: Unexpected value 'FormBuilder' imported by the module 'DynamicTestModule'
        Error: Unexpected value 'FormBuilder' imported by the module 'DynamicTestModule'

【问题讨论】:

【参考方案1】:

我遇到了同样的错误,我想分享我的解决方案以帮助其他人

我在 Karma 中遇到的错误

error properties: Object( ngTempTokenPath: null, ngTokenPath: [ 'RouterModule', 'Router', 'Function', 'Function' ] )
NullInjectorError: R3InjectorError(DynamicTestModule)[RouterModule -> Router -> Function -> Function]: 
  NullInjectorError: No provider for Function!

inventory-view.component.ts

@Component(
  selector: 'app-inventory-view',
  templateUrl: './inventory-view.component.html',
  styleUrls: ['./inventory-view.component.scss'],
  animations: []
)
export class InventoryViewComponent implements OnInit, AfterViewInit, OnDestroy 

  constructor(
    public router: Router, // <--- here was the problem
    public activatedRoute: ActivatedRoute
  )  

在我的测试文件中

inventory-view.component.spec.ts

import  HttpClientModule  from '@angular/common/http';
import  waitForAsync, ComponentFixture, TestBed  from '@angular/core/testing';
import  RouterTestingModule  from '@angular/router/testing';
import  ActivatedRoute, convertToParamMap, Router  from '@angular/router';

const ActivatedRouteSpy = 
  snapshot: 
    paramMap: convertToParamMap(
      some: 'some',
      else: 'else',
    )
  ,
  queryParamMap: of(
    convertToParamMap(
      some: 'some',
      else: 'else',
    )
  )
;

const RouterSpy = jasmine.createSpyObj(
  'Router',
  ['navigate']
);

describe('InventoryViewComponent', () => 
  let component: InventoryViewComponent;
  let fixture: ComponentFixture<InventoryViewComponent>;

  beforeEach(waitForAsync(() => 
    TestBed.configureTestingModule(
      imports: [
        HttpClientModule,
        RouterTestingModule,
      ],
      declarations: [ InventoryViewComponent ],
      providers: [
         provide: ActivatedRoute,   useValue: ActivatedRouteSpy    ,
         provide: Router,           useValue: RouterSpy            
      ]
    )
    .compileComponents();
  ));

  beforeEach(waitForAsync(() => 
    fixture = TestBed.createComponent(InventoryViewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  ));

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

【讨论】:

谢谢,按照您的建议添加 provide: Router, useValue: RouterSpy 解决了我的问题。【参考方案2】:

为configureTestingModule testCase添加RouterTestingModule

==> 导入:[RouterTestingModule],

import RouterTestingModule from '@angular/router/testing';

beforeEach(() => 
TestBed.configureTestingModule(
imports: [RouterTestingModule], // <====
providers: [],
declarations: [],
);
);

【讨论】:

在声明中,提供您的组件名称,如下所示:声明:[YourComponentName]【参考方案3】:

设置测试模块时需要导入RouterTestingModule。

  /* tslint:disable:no-unused-variable */
  import  async, ComponentFixture, TestBed  from '@angular/core/testing';
  import  By  from '@angular/platform-browser';
  import  DebugElement  from '@angular/core';

  import  RouterTestingModule  from '@angular/router/testing';

  import  MyNewComponentComponent  from './my-new-component.component';

  describe('MyNewComponentComponent', () => 
    let component: MyNewComponentComponent;
    let fixture: ComponentFixture<MyNewComponentComponent>;

    beforeEach(async(() => 
      TestBed.configureTestingModule(
        imports: [RouterTestingModule],
        declarations: [ MyNewComponentComponent ]
      )
      .compileComponents();
    ));

    beforeEach(() => 
      fixture = TestBed.createComponent(MyNewComponentComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    );

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

编辑:模拟 DummyService 的示例

  /* tslint:disable:no-unused-variable */
  import  async, ComponentFixture, TestBed  from '@angular/core/testing';
  import  By  from '@angular/platform-browser';
  import  DebugElement  from '@angular/core';

  import  RouterTestingModule  from '@angular/router/testing';

  import  MyNewComponentComponent  from './my-new-component.component';

  // import the service
  import  DummyService  from '../dummy.service';

  // mock the service
  class MockDummyService extends DummyService 
    // mock everything used by the component
  ;

  describe('MyNewComponentComponent', () => 
    let component: MyNewComponentComponent;
    let fixture: ComponentFixture<MyNewComponentComponent>;

    beforeEach(async(() => 
      TestBed.configureTestingModule(
        imports: [RouterTestingModule],
        declarations: [MyNewComponentComponent],
        providers: [
          provide: DummyService,
          useClass: MockDummyService
        ]
      )
        .compileComponents();
    ));

    beforeEach(() => 
      fixture = TestBed.createComponent(MyNewComponentComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    );

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

【讨论】:

在没有实现的情况下扩展 DummyService 的 MockDummyService 会不会利用 DummyService 中的相同方法,从而使模拟毫无意义? @JayChase 你可以发布一个 git 链接,例如你创建的或者 stackblitz 链接,它对所有人都有帮助。

单元测试 typescript 指令模板 karma-jasmine,html 未定义

】单元测试typescript指令模板karma-jasmine,html未定义【英文标题】:unittestingtypescriptdirectivetemplatekarma-jasmine,htmlisnotdefined【发布时间】:2016-06-2401:04:35【问题描述】:最近我开始使用karma-jasmine对我的typescript代码进行单元测试。在... 查看详情

karma-jasmine 在第一次失败后停止单元测试的命令

】karma-jasmine在第一次失败后停止单元测试的命令【英文标题】:Commandforkarma-jasminetostopunit-testafterfirstfail【发布时间】:2015-03-2704:30:18【问题描述】:karma-jasmineunit-test遇到第一个测试失败时,是否有任何命令可以停止测试。例如... 查看详情

为 Preact 编写单元测试用例

】为Preact编写单元测试用例【英文标题】:WritingUnitTestCasesforPreact【发布时间】:2018-04-0419:33:47【问题描述】:我对Preact很陌生,我必须为Preact中的应用程序编写单元测试用例。我可以发现jest和酵素可以用于相同的用途,但我每... 查看详情

java示例代码_为此方法编写单元测试用例

java示例代码_为此方法编写单元测试用例 查看详情

如何在 jasmine 中编写单元测试用例?

】如何在jasmine中编写单元测试用例?【英文标题】:Howtowriteunittestcaseinjasmine?【发布时间】:2021-07-1110:27:36【问题描述】:Flag(a)letelement=this.selected.filter(item=>item.a===a)returnelement.length>1?true:false;不确定如何为上述函数编写单元... 查看详情

如何为 JWT 策略编写单元测试用例

】如何为JWT策略编写单元测试用例【英文标题】:HowtowriteunittestcaseforJWTstrategy【发布时间】:2020-09-1909:05:55【问题描述】:我是新来的passport.js,并试图涵盖我的JWT策略的单元测试用例。任何人都可以建议如何做到这一点?//Setup... 查看详情

我们如何为嵌套函数编写单元测试用例(Jasmine)?

】我们如何为嵌套函数编写单元测试用例(Jasmine)?【英文标题】:HowdowewriteUnittestcases(Jasmine)fornestedfunctions?【发布时间】:2017-05-2902:51:47【问题描述】:我正在为以下场景编写一个测试用例。代码覆盖率没有完全覆盖。不知道... 查看详情

如何使用 Jasmine 为以下 javascript 函数编写单元测试用例

】如何使用Jasmine为以下javascript函数编写单元测试用例【英文标题】:HowtowriteUnitTestCaseforbelowjavascriptfunctionusingJasmine【发布时间】:2019-04-1303:24:37【问题描述】:如何使用Jasmine为下面的javascript函数编写单元测试用例?functionGetURL... 查看详情

Spring Boot:如何为删除其余模板编写单元测试用例

】SpringBoot:如何为删除其余模板编写单元测试用例【英文标题】:Springboot:Howtowriteunittestcasefordeleteresttemplate【发布时间】:2020-11-2120:51:14【问题描述】:我正在尝试为HttpHandler类编写单元测试用例,该类具有用于删除的其余模板... 查看详情

InvalidArgumentException:编写单元测试时出现未知的格式化程序

】InvalidArgumentException:编写单元测试时出现未知的格式化程序【英文标题】:InvalidArgumentException:Unknownformatterwhilewritingunittests【发布时间】:2017-11-1615:09:44【问题描述】:我正在为我们的应用程序编写phpUnit测试,为此我编写了一... 查看详情

为控制器类编写负单元测试用例:spring boot

】为控制器类编写负单元测试用例:springboot【英文标题】:writingnegativeunittestcasesforcontrollerclasses:springboot【发布时间】:2019-11-0509:03:54【问题描述】:有没有办法为控制器类编写一些负面测试用例@RestController@RequestMapping(value="/hea... 查看详情

获取错误:在角度 js 中进行单元测试时出现 $injector:modulerr 模块错误

...2017-01-2302:55:32【问题描述】:我正在尝试用Angular和jasmine编写单元测试用例。运行测试时出现以下错误:varBCM=angular.module("App" 查看详情

软件测试之如何编写单元测试用例

单元测试是以程序设计说明书为指导,测试模块范围内的重要控制路径,以揭露错误。当程序编好以后,将它录制在媒体上,或者直接由终端键盘输入到机中进行调试。测试的相对复杂性和所发现的错误受到单元测试所限定的范... 查看详情

如何使用 Kafka Streams 为应用程序编写单元测试用例

】如何使用KafkaStreams为应用程序编写单元测试用例【英文标题】:HowtowriteunittestcaseforapplicationusingKafkaStreams【发布时间】:2021-08-2114:52:06【问题描述】:我们正在构建一个将使用KafkaStreams的应用程序。我们正在寻找示例示例,该... 查看详情

编写 Gradle 脚本以运行 Eclipse Android 测试项目的单元测试用例

】编写Gradle脚本以运行EclipseAndroid测试项目的单元测试用例【英文标题】:WritingGradlescripttorununittestcasesforEclipseAndroidTestproject【发布时间】:2014-06-2619:12:12【问题描述】:我有一个简单的HelloWorldAndroid项目(内置在EclipseIDE中),... 查看详情

编写单元测试用例说明书的依据是啥

编写单元测试用例说明书的依据是什么一、单元测试的概念单元通俗的说就是指一个实现简单功能的函数。单元测试就是只用一组特定的输入(测试用例)测试函数是否功能正常,并且返回了正确的输出。测试的覆盖种类1.语句覆... 查看详情

在 Objective C 中编写单元测试用例时,在单独的方法中重构 XCTest 断言的代码重复

】在ObjectiveC中编写单元测试用例时,在单独的方法中重构XCTest断言的代码重复【英文标题】:RefactorcodeduplicationofXCTestAssertionsinaseperatemethodwhilewritingunittestcasesinObjectiveC【发布时间】:2018-03-2912:55:32【问题描述】:我有一个包含多... 查看详情

测试代码

  编写函数或类时,还可以为其编写测试。通过测试,可确定代码面对各种输入都能够按照要求那样工作。 单元测试和测试用例: 单元测试用于核实蛮熟的某个方面没有问题;测试用例是一组单元测试,这些单元... 查看详情