0
votes

Below unit test is throwing error : TypeError: Cannot read property 'toString' of undefined. How can this be resolved?

component.Ts code

//Input value from parent

@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;
});
2

2 Answers

0
votes

Add a default value to that @Input() variable depending on your treeDataKey type.

What will this do is, if you donot have the value from input, it will get assigned with an empty value. So, if the parent component is not instantiated at the time of test, the test runs with a default value.

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

Try This:

import {isUndefined} from "util";

  this.testPath = (this.path && !isUndefined(this.path))?
  (this.path).toString().replace(/,/g,' /'):'';