How to use custom babel config for jest?

Friday, September 24, 2021

For Scenario where jest setup is not present in current React Project and you want to use a babel config unrelated to current setup, you can do the following setup.

jest.config.js

module.exports = {
  verbose: true,
  transform: { '^.+\\.js$': '<rootDir>/jestPreprocess.js' },
};

jest.preprocessor.js

const babelOptions = { presets: ['env'] }; // Place you .babelrc related config here

module.exports = require('babel-jest').createTransformer(babelOptions);

NOTE: When using babel-jest < 27, you must omit the .default part: require("babel-jest").createTransformer({ ....

package.json

"scripts": {
    "test": "jest --config jest.config.js --no-cache",
    // ...

No comments: