React 测试库:找不到在 .d.ts 中声明的模块
React testing library: Cannot find module declared in .d.ts
谢谢你的时间。
我对 React 测试库有疑问。一切都在浏览器中工作。我可以构建,但是当 运行 测试 时,jest 找不到 typescript 定义。
如果我使用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"
]
}
我从这个 answer 中找到了解决方案。
Jest 无法识别远程模块。要修复它需要模拟导入的模块:
jest.mock('UI/Button',
() => ({
myFunc: () => 'hello'
}),
{ virtual: true }
);
谢谢你的时间。
我对 React 测试库有疑问。一切都在浏览器中工作。我可以构建,但是当 运行 测试 时,jest 找不到 typescript 定义。
如果我使用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"
]
}
我从这个 answer 中找到了解决方案。 Jest 无法识别远程模块。要修复它需要模拟导入的模块:
jest.mock('UI/Button',
() => ({
myFunc: () => 'hello'
}),
{ virtual: true }
);