Skip to main content

How to Solve the replaceAll error in Jest?

·1 min

One time I was working on a legacy React project, I ran a recently added unit test and I got this error:


Jest: TypeError: replaceAll is not a function

I was confused at the beginning because in the browser the component was working like a charm using replaceAll method, but it turns out that replaceAll is a new function not implemented in all browsers nor older Node.js versions.


Install the replaceAll polyfill and add it to the jest setup configuration file.
  1. Install the replaceAll
npm i string.prototype.replaceall
  1. Modify your Jest config, add a setupFilesAfterEnv property as below:
  "jest": {
    "setupFilesAfterEnv": ["<rootDir>/jestSetup.js"]
  1. Add the following code to your jestSetup file
import replaceAllInserter from 'string.prototype.replaceall';


Happy coding!