You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单元测试报错: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的错误。

修复方案

把测试中的赋值语句改成传入数组类型的值,有两种选择:

  1. 传入完整的测试数组:
component.sourceAccounts = source_accounts;
  1. 如果需要测试单元素场景,把单个对象包装成数组:
component.sourceAccounts = [source_accounts[0]];

额外优化建议

为了避免组件中sourceAccounts未初始化时出现类似错误,可以在组件声明时直接初始化空数组:

sourceAccounts: Array<IObject> = [];

内容的提问来源于stack exchange,提问作者user123456789

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:07:34