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:
Problem
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.
Solution
Install the replaceAll polyfill and add it to the jest setup configuration file.
- Install the replaceAll
npm i string.prototype.replaceall
- Modify your Jest config, add a setupFilesAfterEnv property as below:
{
"jest": {
"setupFilesAfterEnv": ["<rootDir>/jestSetup.js"]
}
}
- Add the following code to your jestSetup file
import replaceAllInserter from 'string.prototype.replaceall';
replaceAllInserter.shim();
Happy coding!