【问题标题】:Create-React-App v3 not running Jest tests with Absolute Imports of other componentsCreate-React-App v3 未使用其他组件的绝对导入运行 Jest 测试
【发布时间】:2019-11-02 14:32:08
【问题描述】:

根据 (https://facebook.github.io/create-react-app/docs/importing-a-component#absolute-imports) 的指导,我尝试在我的项目 (https://github.com/refayathaque/k1y0b1eahsqztk48) 中导入其他组件和库的两个组件上运行 Jest 测试。

在本地运行应用程序时,绝对路径导入工作正常,一切都按预期呈现,但在 Jest 测试期间,我相信绝对路径导入不起作用。

我之前在“.env”文件中使用了“NODE_PATH=src/”,但 CRA3 建议我们不要使用“jsconfig.json”文件。我有“jsconfig.json”文件,但测试仍未运行。下面的代码是我在“jsconfig.json”文件中的代码:

{
    "compilerOptions": {
      "baseUrl": "src"
    },
    "include": ["src"]
}

来自 Jest 的错误消息:

Test suite failed to run

    /Users/refayathaque/Documents/k1y0b1eahsqztk48/node_modules/react-s3/lib/ReactS3.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Signature from "./Signature";
                                                                                                    ^^^^^^^^^

    SyntaxError: Unexpected identifier

【问题讨论】:

    标签: reactjs jestjs babeljs


    【解决方案1】:

    我终于设法解决了这个问题。重要的是rootDirtsconfig.json 中的baseUrl 相同,并且jestmoduleNameMapper 也包含正确的映射。

    这就是我的设置中的工作原理:

    tsconfig.json:

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {},
        "rootDir": ".",
        // ...
      },
      "include": ["."],
      "exclude": [
        // ...
      ]
    }
    

    在您的jest 配置中,无论您是否使用create-react-app 创建应用程序:

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

    我的.env 文件包括:NODE_PATH=src/

    这适用于像这样的导入: import {StyledDropdown} from 'src/components';

    这适用于使用create-react-app (react-scripts-ts@3.1.0) 创建的项目,未弹出,使用typescript@3.7.2

    【讨论】:

      猜你喜欢
      • 2017-07-04
      • 2020-07-22
      • 2019-01-30
      • 2020-03-11
      • 1970-01-01
      • 2020-08-09
      • 2018-02-27
      • 2020-01-11
      • 2020-10-10
      相关资源
      最近更新 更多