如何在角度5中对箭头功能进行单元测试

时间:2018-06-19 12:14:22

标签: angular unit-testing visual-studio-code karma-jasmine

这是我需要测试的ts文件,Karma中未发现的代码仅是以下行

(value => {
      this.value = ++this.value;
    });

我是新来的,对单元测试来说是新来的,请帮助

import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { ToolHandlerService } from '../shared/services/toolhandler.service';
import { ISubscription } from 'rxjs/Subscription';

@Component({
  selector: 'basic-graphicresults',
  templateUrl: './graphicresults.component.html',
  styleUrls: ['./graphicresults.component.scss']
})
export class GraphicResultsComponent implements OnInit, OnDestroy {

  @Input() value: number;
  private replaceResultsSubscription: ISubscription;

  constructor(private toolHandlerService: ToolHandlerService) {
  }

  ngOnInit() {
    this.value=4;
    this.replaceResultsSubscription = this.toolHandlerService.onReplaceResults$.subscribe(value => {
      this.value = ++this.value;
    });
  }

  ngOnDestroy() {
    this.replaceResultsSubscription.unsubscribe();
  }
}

1 个答案:

答案 0 :(得分:1)

尝试在规范文件中创建ToolHandlerService类的模拟类,并将其注入到您的测试平台配置提供程序中,例如

providers: [{provide:ToolHandlerService, UseClass: MockToolHandlerService}]

,然后在您的测试用例中执行以下操作:

let isEventTriggered = false;
toolHandlerService.onReplaceResults$.subscribe(() => {
  isEventTriggered = true;
});
toolHandlerService.replaceResults.next();
expect(isEventTriggered).toBeTruthy();

通过上述操作,您将看到用例被覆盖。

注意:此处使用的ToolHandlerService应该包含MockToolHandlerService的引用