String.prototype.replaceAll()是一个有用的方法,在构建和执行所有东西时都工作得很好。但是,所有Jest-Jest都会失败,并显示以下错误:
TypeError: replaceAll is not a function以下是我的依赖项:
"dependencies": {
"core-js": "^3.6.5",
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-i18n": "^8.22.0",
"vue-property-decorator": "^8.4.2",
"vue-router": "^3.3.4",
"vuex": "^3.5.1"
},
"devDependencies": {
"@vue/test-utils": "^1.1.0",
"jest-junit": "^12.0.0",
"ts-jest": "^26.4.1",
"typescript": "~3.9.3",
"vue-jest": "^3.0.7",
"vue-template-compiler": "^2.6.10"
},我该如何解决这个问题呢?
发布于 2020-12-15 04:07:22
这很可能是因为Node.js中没有实现String.prototype.replaceAll (至少在v14.15.0版本中是这样)。
您可以使用的一个替代方法是正则表达式,如下例所示:
const str = 'foo-foo';
const regex = /foo/g; // Note the 'g' flag, which matches all occurrences of the expression
console.log(str.replace(regex, 'bar')); // 'bar-bar'你可以查看here获取更多关于正则表达式的信息。
发布于 2021-06-08 02:59:58
问题所在
这是因为replaceAll是一个新功能,并不是在所有浏览器中都实现的,也不是在较早的Node.js版本中实现的,正如另一个答案中提到的那样。您可以查看哪些浏览器在Can I Use中支持它

但是,与使用带有RegExp的.replace不同,您可以添加polyfill来支持较旧的浏览器(如果需要)。在我的例子中,我使用的是Electron,所以我只需要在Jest中使用它。
填充程序可以是found here。
解决方案
用作浏览器的polyfill
将
npm i string.prototype.replaceall或yarn add string.prototype.replaceall;的依赖项
import replaceAllInserter from 'string.prototype.replaceall';
replaceAllInserter.shim();仅在Jest中使用
更新Node.js
正如@leonheess在评论中提到的,你可以将Node.js更新到更新的版本。您需要一个使用.replaceAll实现时的version 8.5 from V8的版本。
根据list available on the Node.js website的说法,这两个版本都不使用V8 8.5,但从Node.js 15.0.0开始,使用的是V8 8.6版。因此,请升级到Node.js v15或更高版本。
用作多边形填充
如果您只想为Jest修复这个问题,您可以按照前面提到的in this issue进行操作
与yarn add -D string.prototype.replaceall;或一起作为开发依赖项安装
npm i -D string.prototype.replaceallsetupFilesAfterEnv属性,如下所示:{
"jest": {
"setupFilesAfterEnv": ["<rootDir>/jestSetup.js"]
}
}jestSetup文件中:import replaceAllInserter from 'string.prototype.replaceall';
replaceAllInserter.shim();https://stackoverflow.com/questions/65295584
复制相似问题