Angular中Jest测试报错:TypeError: columnDefs.findLast is not a function
解决Jest测试中
columnDefs.findLast is not a function错误 问题原因
Array.prototype.findLast是ES2022新增的数组方法,你的Jest测试环境(Node.js版本过低或Babel未配置转译)不支持该方法,即使columnDefs是数组,也无法调用这个方法。
解决办法
1. 替换为兼容写法(无需升级或配置)
用数组反转后find的方式替代findLast,逻辑完全等价:
onKeyDown(key: any) { const columnDefs = this.params.columnApi.columnModel.columnDefs; // 复制数组并反转,避免修改原数组 const lastColumnEnabled = [...columnDefs].reverse().find((col: any) => { if (col.cellEditorParams?.hasOwnProperty('isDisabled')) { if ( typeof col.cellEditorParams.isDisabled !== 'function' && col.cellEditorParams.isDisabled === false ) return col; if ( typeof col.cellEditorParams.isDisabled === 'function' && col.cellEditorParams.isDisabled(this.params.data, col.field) === false ) { return col; } } else { return col; } }); }
2. 升级Node.js版本
Node.js从v18.0.0开始原生支持findLast,如果项目允许,直接升级Node.js到18.x或更高版本,无需修改代码即可解决。
3. 配置Babel转译ES2022方法
如果无法升级Node.js,通过Babel插件转译findLast:
- 安装依赖:
npm install --save-dev @babel/plugin-proposal-array-find-last
- 在Babel配置文件(
babel.config.json或.babelrc)中添加插件:
{ "plugins": ["@babel/plugin-proposal-array-find-last"] }
额外验证
确认测试中模拟的columnDefs是真正的数组,而非类数组对象。可在测试代码中添加:
console.log(Array.isArray(columnDefs)); // 应为true
如果是类数组,用Array.from(columnDefs)转换为数组后再调用方法。
内容的提问来源于stack exchange,提问作者Jmainol
相关产品推荐
相关产品推荐

