【问题标题】:Testing route method in Angular unit test returns type error在 Angular 单元测试中测试路由方法返回类型错误
【发布时间】:2021-05-05 02:06:17
【问题描述】:

我正在编写单元测试的 Angular 应用程序。我的组件中有一种方法。

我的组件:

route(element) {
    this.myService.Name(element.Name);
    this.myService.Code(element.Code);
    this.router.navigate(["myPage"], { relativeTo: this.routes});
}
    

我的服务:

Name(data) {
    this.name.next(data);
}

Code(data) {
    this.code.next(data);
}

private code = new BehaviorSubject("");
getCode = this.code.asObservable();

private name= new BehaviorSubject("");
getName = this.name.asObservable();

我的单元测试如下:

it('route() function should be called', () => {
    component.route(mockData[0]);
    var spy = spyOn(component, "route").and.callThrough();
    expect(spy).toBeDefined();
})

我在运行测试用例时遇到以下错误:

TypeError: this.myService.Name 不是函数

我该如何解决这个问题?

【问题讨论】:

  • 你必须模拟myService。你有TestBed.configureTestingModule吗?

标签: angular jasmine karma-jasmine angular8


【解决方案1】:

您需要在测试文件的TestBed 中配置一个测试模块,然后通过将服务类添加到providers 数组中来提供您的服务。

TestBed.configureTestingModule({
  declarations: [ MyComponent ],
  providers: [
    { provide: MyService, useValue: MyService }
  ]
});

您甚至可以通过将另一个类传递给 useValue 属性来伪造正在测试的服务。仅模仿原始行为进行测试的建议。

更多信息请阅读Angular Docs

【讨论】:

    猜你喜欢
    • 2014-11-08
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 2021-07-01
    • 2018-09-23
    • 2018-10-23
    相关资源
    最近更新 更多