【问题标题】:spyOn not working on a dependency in Angular 7 unit testsspyOn 无法处理 Angular 7 单元测试中的依赖项
【发布时间】:2019-10-30 22:11:33
【问题描述】:

我有一个依赖于 SearchAttributeService 的组件。有一个名为searchAttributeValidation 服务的方法返回一个Subject。我正在订阅这个主题:

  attributeSearchValidation(): void {
    this._searchAttributeService.searchAttributeValidation.subscribe((value: string) => {
      if (value === this._searchAttributeService.emptyAttributeSearchData) {
        this.searchAttributeIndicator = true;
      } else if (value === this._searchAttributeService.clearEmptyAttributeSearchDataValidation) {
        this.searchAttributeIndicator = false;
    });
  }

get searchAttributeValidation(): Subject<string> {
   return this.searchAttributeValidationSubject;
}

我正在尝试像这样测试这种方法:

  searchAttributeService = TestBed.get(SearchAttributeService);
  let spy = spyOn(searchAttributeService, 'searchAttributeValidation').and.returnValue(of('EMPTY-DATA'));
  component.attributeSearchValidation();
  expect(spy).toHaveBeenCalled();
  expect(component.searchAttributeIndicator).toBeTruthy();

在测试过程中根本不调用 searchAttributeValidation 方法。我什至提供了服务 TestBed.configureTestingModule({

测试失败并显示以下消息:Expected spy searchAttributeValidation to has been called.

我哪里错了??花了一整天的时间,还是没搞清楚问题?

【问题讨论】:

  • 您在日志中收到的错误是什么?
  • @AjayReddy 应调用间谍 searchAttributeValidation。
  • 'searchAttributeValidation' 是一个可观察的对象,而不是一个方法。 'spyOn' 可用于方法而不是对象。
  • @AshishPatel searchAttributeValidation 是一个 getter 方法,它返回一个可观察的 get searchAttributeValidation(): Subject { return this.searchAttributeValidationSubject; }
  • 您正在模拟服务,然后期望调用实际的服务方法....相反,您需要检查 subscribe 方法中的值的测试,例如 expect(searchAttributeIndicator).toBeTruthy() ...等

标签: angular jasmine karma-jasmine spy angular-test


【解决方案1】:

spyOn 用于方法,但您正在访问一个属性,如果它是一个方法,您将像访问它一样

this._searchAttributeService.searchAttributeValidation().subscribe

带有 call() 参数。

如果它是一个 getter 属性,那么使用 spyOnProperty 或者如果它是一个实例属性,那么重新分配它。

searchAttributeService.searchAttributeValidation = of('EMPTY-DATA');

并摆脱期望已被调用。

【讨论】:

  • 谢谢你的解释,它不起作用。你的解释很到位。
猜你喜欢
  • 2015-04-27
  • 2019-07-11
  • 2020-11-03
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 2018-09-23
相关资源
最近更新 更多