【问题标题】:jest cannot detect absolute paths when using webpack resolvejest 在使用 webpack 解析时无法检测到绝对路径
【发布时间】:2021-04-11 10:53:11
【问题描述】:

运行玩笑测试时出现以下错误:

src/tests/components/ImageSearchApp.test.js
  ● Test suite failed to run

    Cannot find module '@comp/Header' from 'src/components/ImageSearchApp.js'

    Require stack:
      src/components/ImageSearchApp.js
      src/tests/components/ImageSearchApp.test.js

      2 | import React from "react";
      3 | /* ========= Components ============= */
    > 4 | import Header from "@comp/Header";
        | ^
      5 | import { SearchImages } from "@cont/SearchImages";
      6 | import Footer from "@comp/Footer";
      7 | /* ========= Code ============= */

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:306:11)
      at Object.<anonymous> (src/components/ImageSearchApp.js:4:1)

这是在我在 webpack.config.js 中实现解析路径之后开始的

resolve: {
      alias: {
        "@root": path.resolve(__dirname, "./"),
        "@src": path.resolve(__dirname, "src/"),
        "@actions": path.resolve(__dirname, "src/actions"),
        "@comp": path.resolve(__dirname, "src/components"),
        "@cont": path.resolve(__dirname, "src/containers"),
        "@img": path.resolve(__dirname, "src/img"),
        "@reducers": path.resolve(__dirname, "src/reducers"),
        "@selectors": path.resolve(__dirname, "src/selectors"),
        "@store": path.resolve(__dirname, "src/store"),
        "@tests": path.resolve(__dirname, "src/tests"),
        "@consts": path.resolve(__dirname, "src/constants"),
      },
    },

我的绝对路径在我的反应组件中工作正常,我只是无法运行测试。 我的 jest.config.json 看起来像这样:

{
  "setupFiles": ["raf/polyfill", "<rootDir>/src/tests/setupTests.js"],
  "snapshotSerializers": ["enzyme-to-json/serializer"]
}

这就是我在 package.json 中运行测试命令的方式:

"scripts": {
    ...,
    "test": "jest --config=jest.config.json --watch",
    ...
},

最后,我的应用结构:

App
|--dist
|--node_modules
|--src
|   |--components
|   |--tests
|       |--compoenent.test.js
|       |--setupTest.js 
|   |--app.js
|--jest.config.json
|--webpack.config.js
|--package.json

谁能指出我该如何解决这个问题。我想在我的 webpack.config.js 中使用绝对路径

【问题讨论】:

    标签: reactjs webpack jestjs


    【解决方案1】:

    在您的jest.config.json 中,您需要设置moduleNameMapper 属性并映射您在webpack 中设置的相同别名。

    您还可以选择使用modulePaths 设置路径。

    例子:

    "moduleNameMapper": {
        "@root/(.*)": "<rootDir>/$1",
        "@src/(.*)": "<rootDir>/src/$1",
        "@actions/(.*)": "<rootDir>/src/actions/$1",
    }
    

    【讨论】:

    • 谢谢@luissmg 你能用例子说明一下吗?这对那些将在未来寻求答案的人更有用。
    • 当然!希望这对您有所帮助和工作:)
    猜你喜欢
    • 2022-07-05
    • 2017-12-15
    • 1970-01-01
    • 2018-12-27
    • 2021-04-21
    • 1970-01-01
    • 2015-08-05
    • 2021-09-08
    • 2018-02-08
    相关资源
    最近更新 更多