Array.findIndex运行正常但Jasmine单元测试报findIndex is not a function错误
报错原因
Array.prototype.findIndex 是ES2015(ES6)才正式纳入标准的数组实例方法,你直接运行代码的环境已经支持该语法,但Jasmine单元测试运行的宿主环境(比如低版本Node、旧版浏览器、或者配置了低版本语法兼容的测试运行器)没有内置该方法的实现,因此调用时会抛出.findIndex is not a function的错误。
可落地的解决办法
- 方案1:替换为ES5兼容的写法实现相同逻辑,不需要修改测试环境配置,替换后的代码示例如下:
const array2 = [ { id: 1, dev: false }, { id: 2, dev: false }, { id: 3, dev: true } ]; const search = obj => obj.dev === true; // 写法1:用map+indexOf实现 const targetIndex = array2.map(item => item.dev).indexOf(true); // 写法2:手动遍历兼容性最高 /* let targetIndex = -1; for(let i = 0; i < array2.length; i++){ if(search(array2[i])){ targetIndex = i; break; } } */ console.log(targetIndex);
- 方案2:给测试环境增加ES6+语法polyfill,比如引入core-js对应数组方法的垫片,或者升级Jasmine运行的Node/浏览器环境到支持ES6的版本(Node 4.0及以上、Chrome 45及以上均原生支持findIndex方法)。
- 方案3:确认代码中
array2变量在测试执行时确实是数组类型,而非其他没有findIndex方法的对象类型,排除变量被意外覆盖的问题。
内容的提问来源于stack exchange,提问作者Natcha
相关产品推荐
相关产品推荐

