如何解决使用茉莉花和业力进行单元测试时形成数组错误
我正在为角度应用程序版本9编写单元测试用例,但即时消息低于错误。
TypeError:无法读取未定义的属性“ get”
如何监视getFormControls方法,否则我必须使用spyonproperty,我试图设置spyonproperty但出现其他错误。
茉莉花单元测试的新手在大多数地方都被击中,
ts:
get getFormControls() {
const control = this.relTable.get('tableRows') as FormArray;
return control;
}
submit() {
this.messageService.clear();
/* const formGroup = this.getFormControls.controls[this.isEdit.length - 1] as FormGroup;
const rNameValue = formGroup.controls['rName'].value;
const pEntityValue = formGroup.controls['pEntity'].value;
const cEntityValue = formGroup.controls['cEntity'].value;
this.new_rel_Data.push({
'rName': rNameValue,'pEntity': pEntityValue,'cEntity': cEntityValue
}); */
this.new_rel_Data.push({
'rName': this.getFormControls.controls[this.isEdit.length - 1].get('rName').value,'pEntity': this.getFormControls.controls[this.isEdit.length - 1].get('pEntity').value,'cEntity': this.getFormControls.controls[this.isEdit.length - 1].get('cEntity').value
});
this.relTemp.addReldata(this.new_rel_Data).subscribe(
(res) => {
console.log(res);
this.loadRelTemp();
this.messageService.add({ severity: 'success',summary: 'New value inserted successfully',sticky: true });
},(err) => {
this.messageService.add({ severity: 'error',summary: err.message,detail: 'Please contact Admin',() => {
const control = this.relTable.get('tableRows') as FormArray;
control.clear();
this.enableSubmit = false;
}
);
}
规格:
// submit for insert new value
fit('Submit() Relational data',() => {
let data = [ 'foo' ];
component.new_rel_Data = data;
fixture.detectChanges();
spyOn(component,'submit').and.callThrough();
spyOn(relTemplateUpdateService,'addReldata').and.returnValue(
of({ result: { status: 200 } })
);
component.submit();
fixture.detectChanges();
expect(component.submit).toHaveBeenCalled();
expect(relTemplateUpdateService.addReldata).toHaveBeenCalledWith(data);
});
解决方法
当您遇到以下错误:TypeError: Cannot read property 'get' of undefined
时,通常意味着您忘记在测试中添加/模拟某些内容(尽管在真实代码中也可能发生这种情况)。
在这种情况下,您错过了模拟relTable
或getFormControls
getter的结果。
无论如何,我可能会像这样模拟吸气剂:
spyOnProperty(relTemplateUpdateService,'getFormControls').and.returnValue(new FormArray([
new FormGroup({
rName: new FormControl('rName'),pEntity: new FormControl('pEntity'),cEntity: new FormControl('cEntity'),}),]));
由于TypeScript不允许分配给getter,因此您可能需要使用spyOnProperty
方法而不是类似relTemplateUpdateService.getFormControls = ...
的方法。如果不是吸气剂,那么您也可以用相同的返回值嘲笑this.relTable
,但我个人并不认为此方法可以与吸气剂一起使用。
您还应该检查(在实际代码中可能会更好;除非您确定不需要),this.isEdit
始终大于0,否则,您将得到另一个未定义的错误。 / p>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。