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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read 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