配置Jest模仿Webpack解析根并解析别名 [英] Configuring Jest to mimic webpack resolve root and resolve alias

查看:161
本文介绍了配置Jest模仿Webpack解析根并解析别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Webpack& ;;建立项目.笑话.目前,Webpack解决配置会导致Jest测试复杂化.在我的webpack配置中,设置了以下选项:

I am working on setting up a project with Webpack & Jest. At the moment Webpack resolve configurations cause complications with Jest tests. In my webpack config I have the following options set:

  resolve: {
    root: [__dirname + "/src/" ],
    extensions: ['', '.js', '.coffee', '.jsx', '.css', '.scss', '.svg']
  }

这使我需要具有以下内容的资产和模块:

This lets me require assets and modules with:

import UnknownImg from 'assets/unknown';

以上内容实际存在(相对于我的项目根目录)src/assets/unknown.svg.

The above actually lives (relative to my project root) src/assets/unknown.svg.

但是,当我对带有上述行的文件运行测试时,在解析到所需模块/资产的路径时会出错.

However, when I run the test for files with lines like the above I get errors when resolving the path to that required module/asset.

Error: /Users/byronsm/dev/nerve-center/src/components/organisms/system_status.jsx: Cannot find module 'assets/unknown' from '/Users/byronsm/dev/nerve-center/src/components/organisms'

在这种情况下,它似乎正在对导入的模块路径进行相对查找.我有办法让Jest的行为与Webpack一样吗?

In this case it appears to be doing a relative lookup of the imported module path. Is there a way for me to get Jest to behave the same as Webpack?

推荐答案

官方笑话文档中现在提供了一个解决方案.参见 Webpack教程.

A solution is now provided in the official jest docs. See Webpack Tutorial.

简而言之,将modulePaths选项添加到package.json中的jest配置中:

In short, add the modulePaths option to your jest config inpackage.json:

"jest": {
    "modulePaths": ["src"], 
    ...
}

这篇关于配置Jest模仿Webpack解析根并解析别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆