Jest测试因gatsby webpack配置而抛出错误

3
我在我的 Gatsby 的 Webpack 配置中加入了 directory-named-webpack-plugin,这个插件使得导入有和其父目录同名的文件变得可能。例如,我可以使用路径 'components/Link' 代替 'components/Link/Link':
const DirectoryNamedWebpackPlugin = require('directory-named-webpack-plugin');

exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    resolve: {
      plugins: [new DirectoryNamedWebpackPlugin()],
    },
  });
};

但是不幸的是,当我使用jest运行我的测试时,我会得到这样的错误(我还使用绝对导入):

FAIL  src/components/atoms/Link/Link.test.jsTest suite failed to run

    Cannot find module 'components/atoms/Icon' from 'src/components/atoms/Link/Link.js'   
    Require stack:
      src/components/atoms/Link/Link.js
      src/components/atoms/Link/Link.test.js

      3 | import { useAnimation } from 'framer-motion';
      4 | import PropTypes from 'prop-types';
    > 5 | import Icon from 'components/atoms/Icon';
        | ^
      6 | import arrow from 'assets/svgs/icon_arrow.svg';
      7 | import S from './Link.styles';
      8 | import animations from './Link.animations';

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:307:11)
      at Object.<anonymous> (src/components/atoms/Link/Link.js:5:1)

这是我的文件夹结构: enter image description here 有没有解决方案?我对jest配置还不太熟悉。
1个回答

0
在每个文件夹中使用像这样的 index.js,完全忘记 DirectoryNamedWebpackPlugin
import Link from './Link';

export default Link;

这种方法相比使用插件也有其缺点:1)你需要为每个组件创建一个index.js文件;2)尝试在IDE中查看组件声明时,每次都需要经过额外的index.js - Vasiliy Artamonov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接