【问题标题】:React testing library: Cannot find module declared in .d.tsReact 测试库:找不到在 .d.ts 中声明的模块
【发布时间】:2021-12-13 19:38:42
【问题描述】:

感谢您的宝贵时间。

我对反应测试库有疑问。一切都在浏览器中工作。我可以构建,但运行测试时,开玩笑找不到打字稿定义。

如果我使用 React lazy 导入组件,不会出现错误。

在我的情况下是UI.d.ts。 UI 来自 webpack 模块联合:

new ModuleFederationPlugin({
    name: "root",
    filename: "remoteEntry.js",
    remotes: { UI: process.env.UI_REMOTE_URL },
    shared: {
        ...deps,
        react: {
            singleton: true,
            requiredVersion: deps.react
        },
        "react-dom": {
            singleton: true,
            requiredVersion: deps["react-dom"]
        }
    }
}),

UI.d.ts 在根目录中。项目树:

├── README.md
├── UI.d.ts
├── package.json
├── public/
├── src/
├── tsconfig.json
├── webpack.config.js
├── yarn-error.log
└── yarn.lock

tsconfig.json:

{
  "exclude": [
    "node_modules",
    "./packages/**/node_modules"
  ],
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "jsx": "react-jsx"
  },
  "include": [
    "src",
    "**/*.d.ts"
  ]
}

【问题讨论】:

  • 您的jest.config.js 文件是什么样的?
  • 这是 CRA 项目

标签: reactjs typescript jestjs react-testing-library


【解决方案1】:

我从这个answer 中找到了解决方案。 Jest 无法识别远程模块。要修复它需要模拟导入的模块:

jest.mock('UI/Button',
  () => ({
    myFunc: () => 'hello'
  }),
  { virtual: true }
);

【讨论】:

    猜你喜欢
    • 2019-12-29
    • 2022-07-12
    • 2019-03-16
    • 2019-07-26
    • 2021-02-21
    • 2019-08-09
    • 2017-05-29
    • 1970-01-01
    • 2022-06-12
    相关资源
    最近更新 更多