【发布时间】:2020-10-09 06:53:57
【问题描述】:
我用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 配置?
【问题讨论】:
-
只需要查找
create-react-library并查看它是用于创建库的,所以我想,是的,也许semantic-ui没有安装在测试运行的地方,想问一下您的 package.json 文件并看到它被列为对等依赖项,而不是常规或开发依赖项。它可能还需要是常规依赖项。 -
我观察到与
create-react-app相同的行为。 (我在原来的帖子之后发现,否则我会参考 CRA,因为它更常用。)