Jestjs 运行Jest单元测试时找不到声明的模块

Jestjs 运行Jest单元测试时找不到声明的模块,jestjs,spfx,Jestjs,Spfx,我正在尝试测试spfx Web部件组件,出现以下错误: Test suite failed to run Cannot find module 'WebPartContentStrings' from 'WebContentContainer.tsx' 我做了一些挖掘,发现在我的组件中,我做了以下工作: import * as strings from "WebPartContentStrings"; 我有这个档案: declare module 'WebPartContentSt

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

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导入字符串?

我也遇到了同样的问题。当在tsconfig.json中对“jsx”属性进行“react”时,必须修复该问题

例如:

{
  "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"
  ]
}
而不是做

将*作为字符串从“WebPartContentString”导入

将Web部件的字符串作为道具传递给组件,并以使用普通道具的方式使用这些字符串。例如:

{
  "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"
  ]
}
道具接口定义:

export interface IYourComponentsProps { strings: IWebPartContentStrings }
在react组件的渲染函数中使用一些字符串:

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

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

干杯