![](/img/trans.png)
[英]Unit Testing Custom React Hooks in TypeScript using Jest and @testing-library/react-hooks
[英]Custom React Component Library - jest 'cannot find module react'- testing-library, rollup
我正在构建一个自定义 React 组件库以与其他应用程序共享。 我正在使用汇总并关注此博客和其他一些博客: https://dev.to/alexeagleson/how-to-create-and-publish-a-react-component-library-2oe
我的汇总配置的相关片段如下:
export default [
{
input: "src/index.ts",
output: [ { file: packageJson.main, format: "esm", sourcemap: true } ],
plugins: [ peerDepsExternal(), resolve(), terser() ],
external: ["react", "react-dom"]
}
]
在我的 package.json 中,我已将 react 和 react-dom 从“devDependencies”移动到“peerDependencies”。 我的缩写 package.json:
{
"name": "custom components",
"version": "1",
"devDependencies": {
...stuff, (but not react/react-dom)
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
"main": "dist/esm/index.js",
"files": ["dist"]
}
然后使用npm link
我将我的组件库导入到另一个使用 CRA 和 react-testing-library 的应用程序中。
到目前为止这有效。 我能够按预期渲染我的通用组件。
然而,似乎将 react/react-dom 移出 devDependencies 使我的 jest 测试在两个项目中都失败了。 在这两种情况下,开玩笑都找不到反应。 我的CRA中导入组件的Jest output如下:
Test suite failed to run
Cannot find module 'react' from 'index.js' //<-- this is the index of the component library
However, Jest was able to find:
.../MyComponent.tsx
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js',...etc] (defaults)
当我在公共组件库中运行测试时:
Test suite failed to run
Cannot find module 'react' from 'MyComponent'
import React from 'react';
^
我不确定如何解决这个问题。 如果我将 react/react-dom 移回 devDependencies,测试将成功运行,但是由于项目中有多个 React 副本,任何使用 react state 的组件都将无法呈现。
这可能是一个问题,因为我使用的是 npm 链接,而不是实际将应用程序发布到 npm 并安装,或者这是我的 rollup config/jest config/package.json 的问题吗? 任何帮助,将不胜感激。
react
和react-dom
应该包含在你的库的devDependencies
和peerDependencies
中。
将它们包含在devDependencies
中可以使它们在开发时(以及运行测试时)可用,但是当您将它们与 Rollup 捆绑在一起时(这正是您想要的),它们将不会包含在库中。
将它们包含在peerDependencies
中会告诉任何消费应用程序“您必须在指定的版本范围内拥有这些依赖项”,但同样,Rollup 不会将它们包含在库包中。
如果您只将它们包含在peerDependencies
中,则在开发库或运行测试时不会安装它们,但如果您使用 npm v7 则可能不再如此。
如果你的应用程序包含的 React 版本与你的库版本不同,你可能会遇到项目中有多个 React 版本的问题,但如果应用程序和库的版本范围相同,你就不应该遇到这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.