![](/img/trans.png)
[英]Cannot find module '@jest/globals' in a vue test using jest
[英]Jest test runs - Cannot find module error
我一直在研究 React Typescript 存储库,并且遇到了一个烦人的问题,在开玩笑中无法解析相对于根目录的导入。
Cannot find module '~lib/dates' from 'utils.ts'
这就是组件/工具中导入的样子
import { abc } from '~lib/dates'; // this fails to run
如果我将其更改为相对路径 jest 测试运行按预期工作
import { abc } from '../../lib/dates'; // this runs as expected
相同的路径适用于其他一些目录,我有点难住
import { xyz } from '~components/home/constants'; // jest resolves it
import { abc } from '~lib/dates'; // ERR
我尝试在 jestConfig 中包含moduleNameWrapper
以查看它是否可以正确解析导入,但它没有帮助。
包.json
"jest": {
...
"moduleNameWrapper": {
"^~(.*)$": "<rootDir>/src/$1"
}
}
我可以肯定地更新 VS 代码设置,以便自动导入相对于文件而不是根目录来解析,但这一直困扰着我一段时间。 如果有人对如何最好地解决这个问题有任何指示,那就太好了。
我在具有以下目录结构的 monorepo
repo
server
client
src
components
lib
utils
package.json
你的实现看起来是正确的。 但看起来选项moduleNameWrapper
是错误的选项,它应该是moduleNameMapper
。
我也有一个和你一样的例子,它也使用 babel 作为转换器,当我添加moduleNameMapper
它工作正常。 这是我的例子:
玩笑配置:
https://github.com/tmhao2005/lerna-demo/blob/master/packages/helper/jest.config.js
这是用于测试的文件:
https://github.com/tmhao2005/lerna-demo/blob/master/packages/helper/src/index.ts https://github.com/tmhao2005/lerna-demo/blob/master/packages/helper/src /index.test.ts
忘记~
字符;
首先定义根目录来开玩笑(即src/
);
然后从那个根目录导入你的东西; (例如import { abc } from 'lib/dates'
)
顺便说一句,您始终可以从默认根目录导入您的内容,而无需进行任何如下配置: import { abc } from 'src/lib/dates'
如果您使用的是 create-react-app jest 绝对导入,请进一步阅读
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.