Jest: TypeError: replaceAll is not a function



String.prototype.replaceAll() is a useful method and while building and executing everything works fine. However, all Jest-tests fail with the following error:

TypeError: replaceAll is not a function

These are my dependencies:

"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"
},

How can I fix this behavior?

Answer

This most likely happens because String.prototype.replaceAll is not implemented in Node.js (at least as of version v14.15.0).

One alternative you could use are regular expressions like in this example:

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'

You can check here for more info on regular expressions.



Source: stackoverflow