首页 > 解决方案 > 笑话:TypeError:replaceAll 不是函数

问题描述

String.prototype.replaceAll()是一种有用的方法,在构建和执行时一切正常。但是,所有 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"
},

我该如何解决这种行为?

标签: javascriptnode.jsjestjs

解决方案


这很可能发生,因为String.prototype.replaceAll没有在 Node.js 中实现(至少从 version 开始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'

您可以在此处查看有关正则表达式的更多信息。


推荐阅读