【问题标题】:Unit test : Cannot read property 'toString' of undefined单元测试:无法读取未定义的属性“toString”
【发布时间】:2018-03-27 10:55:39
【问题描述】:

下面的单元测试抛出错误:TypeError:无法读取未定义的属性“toString”。如何解决?

component.Ts 代码

//来自父级的输入值

@Input() path: treeDataKey;
ngOnInit() {
  this.getTestPlanData(this.testId);
  this.testPath = (this.path).toString().replace(/,/g,' /');
}
getTestPlanData(param:any) {
  //Do something
}

component.spec.ts

it('should call getTestPlanData', () => {
    expect(component.getTestPlanData).toHaveBeenCalled;
});

【问题讨论】:

    标签: angular angular-ui-router karma-jasmine


    【解决方案1】:

    根据您的treeDataKey 类型为该@Input() 变量添加一个默认值。

    如果你没有来自input 的值,它将被分配一个empty value。 因此,如果parent component 在测试时未实例化,则测试将使用默认值运行。

    @Input() path: treeDataKey = "";
    ngOnInit() {
      this.getTestPlanData(this.testId);
      this.testPath = (this.path).toString().replace(/,/g,' /');
    }
    getTestPlanData(param:any) {
      //Do something
    }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      import {isUndefined} from "util";
      
        this.testPath = (this.path && !isUndefined(this.path))?
        (this.path).toString().replace(/,/g,' /'):'';
      

      【讨论】:

        猜你喜欢
        • 2019-12-30
        • 2017-06-16
        • 2021-12-02
        • 2017-10-13
        • 1970-01-01
        • 1970-01-01
        • 2021-04-09
        • 2020-08-01
        • 2020-01-17
        相关资源
        最近更新 更多