Jestjs CRA和x2B;纱线2和x2B;jsconfig.json=Can';t运行单元测试

Jestjs CRA和x2B;纱线2和x2B;jsconfig.json=Can';t运行单元测试,jestjs,create-react-app,yarnpkg-v2,vscode-jsconfig,Jestjs,Create React App,Yarnpkg V2,Vscode Jsconfig,我的jsconfig.json文件中有以下配置: { “编译器选项”:{ “baseUrl”:“../src” }, “包括”:[“src”] } 这让我可以这样做: 从“组件”导入{App} 从“操作/应用程序操作”导入*作为操作 与此相反: 从“../components”导入{App} 将*作为操作从“../actions/app.actions”导入 为了开始单元测试,我在src/components/tests 从'@testing library/react'导入{render

我的
jsconfig.json
文件中有以下配置:

{
“编译器选项”:{
“baseUrl”:“../src”
},
“包括”:[“src”]
}
这让我可以这样做:

从“组件”导入{App}
从“操作/应用程序操作”导入*作为操作
与此相反:

从“../components”导入{App}
将*作为操作从“../actions/app.actions”导入
为了开始单元测试,我在
src/components/tests

从'@testing library/react'导入{render}
从“组件”导入{App}
它('渲染而不崩溃',()=>{
render()
})
然而,当我运行
纱线测试
(这是
反应脚本测试
)时,它抛出了一个丑陋的错误:

 FAIL  src/components/tests/App.test.jsx
  ● Test suite failed to run

    Your application tried to access components, but it isn't declared in your dependencies; 
this makes the require call ambiguous and unsound.

    Required package: components (via "components")
    Required by: C:\Users\Summer\Code\sandbox\src\components\tests\

      23714 |     enumerable: false
      23715 |   };
    > 23716 |   return Object.defineProperties(new Error(message), {
            |                                  ^
      23717 |     code: { ...propertySpec,
      23718 |       value: code
      23719 |     },

      at internalTools_makeError (.pnp.js:23716:34)
      at resolveToUnqualified (.pnp.js:24670:23)
      at resolveRequest (.pnp.js:24768:29)
      at Object.resolveRequest (.pnp.js:24846:26)
似乎Jest(或Thread?)认为
components
是一个节点包,因为它不知道我的
jsconfig.json
中的绝对导入设置。有没有办法让它意识到?或者我必须在0%覆盖率和相对导入之间进行选择

我已经试着在我的
包中的
“jest”
下输入
“moduleNameMapper”
,就像文档中解释的那样,但是没有帮助。我犯了同样的错误,之后又犯了一个

我还尝试将测试文件中的
组件
更改为
。/components
,但随后它会抱怨
组件中的
操作/app.actions

模块名称映射器配置:

/*package.json*/
{
/* ... */
“笑话”:{
“moduleNameMapper”:{
“操作(.*)$”:“/src/actions$1”,
“资产(.*)$”:“/src/assets$1”,
“组件(.*)$”:“/src/components$1”,
“mocks(.*)$”:“/src/mocks$1”,
“pages(.*)$”:“/src/pages$1”,
“减速机(.*)$”:“/src/reducers$1”,
“scss(.*)$”:“/src/scss$1”,
“存储(.*)$”:“/src/store$1”,
“主题(.*)$”:“/src/themes$1”,
“api”:“/src/api.js”,
}
}
}

这是因为纱线控制分辨率管道,因此不知道来自第三方配置的分辨率指令(如
moduleNameMapper

但这并不是说你没有选择,具体来说,这里的修复方法是避免使用
moduleNameMapper
,而是利用内置的
链接:
依赖协议。这还有其他优点,例如与所有工具(TS、Jest、ESLint等)兼容,而无需将别名移植到每个配置格式


另请参见:

您是否可以共享您尝试过的配置
moduleNameMapper
?@tmhao2005确定我会将其编辑到问题中。事情看起来很好。你有最小可复制回购协议吗?@tmhao2005还没有。我有点希望我不是唯一一个在VS代码中使用CRA的人,在绝对导入的情况下在纱线2上使用CRA,并开玩笑地编写单元测试。