reactjs - 为什么 Jest 无法运行引用 npm 包的测试?
问题描述
我用create-react-library创建了一个新项目。我正在尝试使用 Jest 和 Enzyme 添加单元测试。我的测试适用于一个简单的组件,但 Jest 无法测试引用semantic-ui-react的组件。
该测试有效:
// src/VanillaComponent.test.js
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
const VanillaComponent = () => <div>Test</div>;
test('Enzyme can render a vanilla component', () => {
expect(shallow(<VanillaComponent />)).toBeDefined();
});
此测试不起作用:
// src/SemanticComponent.test.js
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { Button } from 'semantic-ui-react';
Enzyme.configure({ adapter: new Adapter() });
const SemanticComponent = () => <Button>Test</Button>;
test('Enzyme can render a semantic-ui-react component', () => {
expect(shallow(<SemanticComponent />)).toBeDefined();
});
当我npm test
在上面的测试中运行时,我收到以下错误:
● Test suite failed to run
Cannot find module 'semantic-ui-react' from 'SemanticComponent.test.js'
> 4 | import { Button } from 'semantic-ui-react';
| ^
文件的相关部分package.json
(删除了许多不相关的内容):
{
"scripts": {
"test": "run-s test:unit test:lint test:build",
"test:build": "run-s build",
"test:lint": "eslint .",
"test:unit": "cross-env CI=1 react-scripts test --env=jsdom",
"test:watch": "react-scripts test --env=jsdom"
},
"peerDependencies": {
"react": "^16.0.0",
"semantic-ui-react": "^0.88.2"
},
"devDependencies": {
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "^3.4.1"
},
}
我怎样才能让第二个测试运行?我错过了一些 Jest 配置吗?
解决方案
问题是我在文件中引用semantic-ui-react
为对等依赖项。package.json
我找到了这个答案,这导致我将其添加semantic-ui-react
为对等依赖项和开发依赖项。进行更改后,测试工作正常。
这个解决方案对我来说不是很干净,但我预计不会有任何问题,所以我现在将采用这种方法。
推荐阅读
- java - OpenAPI Generator/Swagger Codegen 中的嵌套属性继承
- flutter - 如何从设备获取或选择本地 GIF 文件
- android - 无法使用“mobile-ffmpeg”/“ffmpeg-kit”修剪我的视频
- http - 如何使用 funcmap 从函数中获取值并将其映射到 gohtml?
- bash - 在没有特定字符串全局否定的情况下复制所有文件
- reactjs - typescript 数组处理中的类型不匹配
- javascript - 与 Angular 10 深度相等的 2.0.5 库集成
- ios - 来自 xcassets 的 UIImage 返回 nil
- minikube - 使用 ingress 访问远程 Kubernetes 集群中的演示服务
- algorithm - 集装箱配送问题