【问题标题】:Cannot find a declared module when running a Jest unit test运行 Jest 单元测试时找不到声明的模块
【发布时间】:2021-03-10 20:02:38
【问题描述】:

我正在尝试测试 spfx webpart 组件,但出现以下错误:

Test suite failed to run

    Cannot find module 'WebPartContentStrings' from 'WebContentContainer.tsx'

我做了一些挖掘,发现在我的组件内部我做了以下事情:

import * as strings from "WebPartContentStrings";

我有这个文件:

declare module 'WebPartContentStrings' {
  const strings: IWebPartContentStrings;
  export = strings;
}

但是,当我模拟组件时,Jest 似乎无法正确解释导入指令并且无法找到该模块,即使当我将其托管在服务器上时应用程序可以找到它。有没有办法以不同的方式为 Jest 导入字符串?

【问题讨论】:

    标签: jestjs spfx


    【解决方案1】:

    我遇到了同样的问题。必须在“反应”tsconfig.json 中的“jsx”属性时修复它。

    例如:

    {
      "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "moduleResolution": "node",
        "jsx": "react",
        "types": ["jest", "node"],
        "lib": [
          "dom",
          "dom.iterable",
          "esnext"
        ],
        "strict": true,
        "noEmit": true,
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "isolatedModules": true,
        "resolveJsonModule": true
      },
      "exclude": [
        "node_modules"
      ],
      "include": [
        "next-env.d.ts",
        "**/*.ts",
        "**/*.tsx"
      ]
    }
    

    【讨论】:

      【解决方案2】:

      而不是做

      从“WebPartContentStrings”导入 * 作为字符串;

      将 webpart 的字符串作为 props 传递给组件,并像使用普通 props 一样使用这些字符串。例如:

      Props 接口定义:

      export interface IYourComponentsProps { strings: IWebPartContentStrings }
      

      在你的 react 组件的渲染函数中使用一些字符串:

      <p>{this.props.strings.exampleString}</p>
      

      这将解决您面临的导入问题。

      干杯。

      【讨论】:

        猜你喜欢
        • 2019-10-30
        • 2022-06-12
        • 2019-04-29
        • 1970-01-01
        • 2020-04-25
        • 2019-03-24
        • 1970-01-01
        • 1970-01-01
        • 2021-12-13
        相关资源
        最近更新 更多