使用ts-jest测试React组件时遇TypeError: array.findLast is not a function
解决Jest测试中
array.findLast is not a function报错问题 问题原因
Array.prototype.findLast是ES2022新增的数组方法,你当前使用的jest-environment-jsdom测试环境并未内置该方法的支持。业务代码能正常运行是因为浏览器原生支持该方法,或者构建流程中添加了对应的polyfill,但测试环境缺少这一步。
解决方案
方案1:使用core-js添加polyfill
- 安装core-js依赖
npm install core-js --save-dev
- 创建测试前置文件
src/setupTests.ts,添加polyfill引入
import 'core-js/es/array/find-last';
- 修改
jest.config.ts,配置测试启动时加载该文件
import type { Config } from "jest"; const config: Config = { verbose: true, collectCoverage: true, coverageDirectory: "coverage", coverageProvider: "v8", testEnvironment: "jsdom", transform: { "^.+\\.tsx?$": ["ts-jest", { tsconfig: "./tsconfig.json" }], }, testRegex: "(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], fakeTimers: { enableGlobally: true }, // 新增配置:加载测试前置文件 setupFilesAfterEnv: ["<rootDir>/src/setupTests.ts"] }; export default config;
方案2:手动添加polyfill
如果不想额外安装依赖,可以在setupTests.ts中手动实现findLast的polyfill:
// 为Array.prototype添加findLast方法的polyfill if (!Array.prototype.findLast) { Array.prototype.findLast = function<T>( predicate: (value: T, index: number, array: T[]) => boolean, thisArg?: any ): T | undefined { for (let i = this.length - 1; i >= 0; i--) { if (predicate.call(thisArg, this[i], i, this)) { return this[i]; } } return undefined; }; }
同样需要在jest.config.ts中配置setupFilesAfterEnv指向该文件。
方案3:升级相关依赖(可选)
部分高版本的jest-environment-jsdom已经内置了对ES2022方法的支持,可以尝试升级依赖:
npm update jest jest-environment-jsdom
升级后若问题解决,无需添加polyfill。
内容的提问来源于stack exchange,提问作者kyrers
相关产品推荐
相关产品推荐

