【问题标题】:how to unit test an arrow function in angular 5如何在角度 5 中对箭头函数进行单元测试
【发布时间】:2018-06-19 12:14:21
【问题描述】:

这里是我需要测试的ts文件,Karma中未发现的代码只有下面一行

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

我是 Angular 新手,对单元测试完全陌生,请帮忙

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();
  }
}

【问题讨论】:

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


    【解决方案1】:

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

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

    然后在你的测试用例中这样做:

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

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

    注意:这里使用的 ToolHandlerService 应该持有 MockToolHandlerService 的引用

    【讨论】:

    • 您对如何测试这样的属性有任何想法:cellRenderer: params => { if (params.value != ' ') { var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(2, 2)); var dateData = moment(params.value).format('M/D'); return (dateData + "/" + twoDigitsCurrentYear); } else { return params.value; } }
    • 您可以使用虚拟值创建一个模拟对象,并通过在方法或订阅中传递它来测试实际和预期的输出。
    猜你喜欢
    • 2021-05-21
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2019-05-15
    • 2021-03-11
    • 2019-04-21
    • 2019-12-28
    相关资源
    最近更新 更多