简体   繁体   中英

Error to execute component test with react-test-renderer and storybook in a react app

I doing the storybook tutorial<\/a> , but in the part of the tutorial when I created and ran the tests, this throws an exception indicating the following error in the file .storybook\/config.js<\/strong> :

react-scripts test
FAIL src/storybook.test.js
Test suite failed to run

TypeError: require.context is not a function

  2 | import "../src/index.css";
  3 |
> 4 | const req = require.context("../src", true, /\.stories.js$/);
    |                     ^
  5 |
  6 | function loadStories() {
  7 |   req.keys().forEach(filename => req(filename));

  at Object.context (.storybook/config.js:4:21)
  at configure (node_modules/@storybook/addon-storyshots/dist/frameworks/configure.js:38:11)
  at Object.load (node_modules/@storybook/addon-storyshots/dist/frameworks/react/loader.js:26:26)
  at loadFramework (node_modules/@storybook/addon-storyshots/dist/frameworks/frameworkLoader.js:31:17)
  at testStorySnapshots (node_modules/@storybook/addon-storyshots/dist/api/index.js:53:36)
  at Object.<anonymous> (src/storybook.test.js:2:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        6.812s
Ran all test suites related to changed files.

You should use requireContext instead of require.context :

Add the package to dev dependencies:

yarn add --dev require-context.macro

and Import it in the config and use it, your config should look like gthis:

import { configure } from "@storybook/react";
import requireContext from 'require-context.macro';

import "../src/index.css";

const req = requireContext('../src', true, /\.stories\.js$/);

function loadStories() {
  req.keys().forEach(filename => req(filename));
}

configure(loadStories, module);

运行这一行: yarn add --dev require-context.macro

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM