storybook: require.context is not a function, snapshots, CRA 2

If you are reporting a bug or requesting support, start here:

Bug or support request summary

Bug

After updating to Create React App 2.0 I can no longer run snapshot tests with yarn test. I get the following error

  ● Test suite failed to run

    TypeError: require.context is not a function

      1 | import { configure } from '@storybook/react';
      2 |
    > 3 | const req = require.context('../src', true, /\^*.stories.js$/);
        |                     ^
      4 |
      5 | import '../src/styles/main.css';
      6 |

      at Object.context (.storybook/config.js:3:21)
      at configure (node_modules/@storybook/addon-storyshots/dist/frameworks/configure.js:37:11)
      at Object.load (node_modules/@storybook/addon-storyshots/dist/frameworks/react/loader.js:24:26)
      at loadFramework (node_modules/@storybook/addon-storyshots/dist/frameworks/frameworkLoader.js:41:17)
      at testStorySnapshots (node_modules/@storybook/addon-storyshots/dist/api/index.js:44:53)
      at Object.<anonymous> (src/storybook.test.js:6:1)

Steps to reproduce

The code is written exactly as explained in the Quick Star Guide under structural testing https://storybook.js.org/testing/structural-testing/ and was working fine before I upgraded to CRA2. I also updated the versions of Storybook to the latest Beta. And I am also using the new SVG import syntax in CRA2 so I’m not sure which of these things has caused the issue.

Please specify which version of Storybook and optionally any affected addons that you’re running

@storybook/addon-actions”: “^4.0.0-alpha.24”, “@storybook/addon-knobs”: “^4.0.0-alpha.24”, “@storybook/addon-links”: “^4.0.0-alpha.24”, “@storybook/addon-storyshots”: “^4.0.0-alpha.24”, “@storybook/addons”: “^4.0.0-alpha.24”, “@storybook/react”: “^4.0.0-alpha.24”,

I read in the Storyshot documentation that you may need to add registerRequireContextHook to your Jest test setup. This was not needed before I made the changes as mentioned above. And as I am using CRA, I only have access to setupTests.js and no way of adding a plugin to the jest babelrc file afaik.

Any help would be really appreciated

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 4
  • Comments: 21 (7 by maintainers)

Most upvoted comments

@semb09, The solution that I’m using doesn’t require react-app-rewired, only babel-plugin-require-context-hook.

jest.config.js

...
  setupTestFrameworkScriptFile: '<rootDir>/testing/setupTestFramework.js',
  transform: {
    '^.+\\.jsx?$': '<rootDir>/testing/transform.js'
  },
...

testing/transform.js

const babelOptions = {
  presets: ['@babel/preset-react', '@babel/preset-env'],
  plugins: ['require-context-hook', 'react-hot-loader/babel', '@babel/plugin-proposal-class-properties']
};

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

testing/setupTestFramework.js

import registerRequireContextHook from 'babel-plugin-require-context-hook/register';
import '@babel/polyfill';

registerRequireContextHook();

I do not have a .babelrc or webpack.config.js in my .storybook directory

require.context is a webpack’s feature. It was supported before in Storyshots but caused a lot of maintenance troubles and bugs. So Babel currently is the right way to polyfill this behavior.

I think you can put .babelrc at the root level with something like this:

{
  "env": {
    "test": {
      "plugins": ["babel-plugin-require-context-hook"]
    }
  }
}

Thanks. I’m not entirely sure why but the following seems to have fixed the issue 🤞 -

  • Added react-app-rewired to app
  • Replaced react-scripts with react-app-rewired in package.json scripts (as mentioned in react-app-rewired docs)
  • Created an empty file named config-overrides.js in route dir (this is required for react-app-rewired to run). I placed no configuration in this file at all.
  • Added custom babelrc file to .storybook directory as above
  • Added import registerRequireContextHook from 'babel-plugin-require-context-hook/register'; registerRequireContextHook(); to setupTests.js in src folder

As I did not actually add any overrides I did not need to use customize-cra. If I remove react-app-rewired the issue re-appears.

@ecsmyth thank you for your solution! I tailored it for my TypeScript needs. my transform.ts looks this way:

const babelOptions = {
    plugins: ['require-context-hook'],
};

module.exports = require('ts-jest').createTransformer({ babelConfig: babelOptions });

For those who stumble onto d3bgger’s issue:

const req = process.env.NODE_ENV === 'test' ? requireContext('../src', true, /\.stories.js$/) : require.context('../src', true, /\.stories.js$/);

If you’re having trouble with require-context.macro, here’s a workaround that worked for me.

Install babel-plugin-macros:

yarn add --dev babel-plugin-macros

And add this to a .babelrc in your project root or .storybook directory:

{
  "plugins": ["macros"]
}

@mAAdhaTTah, my solution will not work with CRA2 unless you eject or fork react-scripts. Up to you to determine if either of those options is better for you than @semb09’s approach.

With CRA2, you can set up the test environment by creating the file src/setupTests.js. This is where you would add the code in the testing/setupTestFramework.js file. However, looking at how the react-scripts package creates the Jest config (<rootDir>/node_modules/react-scripts/scripts/utils/createJestConfig.js) and Babel transformer (<rootDir>/node_modules/react-scripts/config/jest/babelTransform.js), I don’t see a way to add the require-context-hook babel plugin.