单元测试报错:this.sourceAccounts.find is not a function
解决
this.sourceAccounts.find is not a function单元测试错误 错误原因
组件里sourceAccounts被声明为Array<IObject>类型,依赖数组的find方法做数据查找,但单元测试里错误地把单个对象赋值给了这个变量:
component.sourceAccounts = source_accounts[0];
单个对象没有数组的find方法,所以当ngOnInit里订阅的accountNameUpdated$触发时,调用this.sourceAccounts.find()就会抛出is not a function的错误。
修复方案
把测试中的赋值语句改成传入数组类型的值,有两种选择:
- 传入完整的测试数组:
component.sourceAccounts = source_accounts;
- 如果需要测试单元素场景,把单个对象包装成数组:
component.sourceAccounts = [source_accounts[0]];
额外优化建议
为了避免组件中sourceAccounts未初始化时出现类似错误,可以在组件声明时直接初始化空数组:
sourceAccounts: Array<IObject> = [];
内容的提问来源于stack exchange,提问作者user123456789
相关产品推荐
相关产品推荐

