DEV Community

chris-czopp
chris-czopp

Posted on

How to override create-react-app jest config w/t restrictions

The below snippet allows you to override react testing library to pass custom global variables to your jest tests. Sure, it is a hack but this way you can override any jest args without ejecting from create-react-app. Just run it instead of the standard test script 😉.

const fs = require('fs')
const vm = require('vm')
const jest = require('jest')

const extractJestArgsFromReactTestScript = () => {
  const sandbox = vm.createContext({
    capturedArgs: null,
    console,
    process,
    require: path => (
      require(path[0] === '.' ? `${__dirname}/../node_modules/react-scripts/scripts/${path}` : path)
    ),
    __dirname: `${__dirname}/../node_modules/react-scripts/scripts`
  });

  const testScriptContent = fs.readFileSync(`${__dirname}/../node_modules/react-scripts/scripts/test.js`, 'utf8')

  const scriptAsArray = testScriptContent
    .trim()
    .split('\n')

  scriptAsArray.pop()
  scriptAsArray.push('capturedArgs = argv')

  const scriptToRun = scriptAsArray.join('\n')

  vm.runInContext(scriptToRun, sandbox)

  return sandbox.capturedArgs
};

const capturedArgs = extractJestArgsFromReactTestScript()
const jestConfigValueArgIndex = capturedArgs.findIndex(arg => arg === '--config') + 1
const jestOverriddenConfig = JSON.parse(capturedArgs[jestConfigValueArgIndex])
const overriddenArgs = [...capturedArgs]

jestOverriddenConfig.globals = Object.assign(jestOverriddenConfig.globals || {}, {
  someGlobal: 'hello!'
})

overriddenArgs[jestConfigValueArgIndex] = JSON.stringify(jestOverriddenConfig)

jest.run(overriddenArgs)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)