DEV Community

chris-czopp
chris-czopp

Posted on

1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more