我用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配置?
答案 0 :(得分:0)
问题是我在// Tried so far
const seen = new Set();
const fa = arr.filter((el) => {
const duplicate = seen.has(el.id);
seen.add(el.id);
return !duplicate;
});
文件中引用了semantic-ui-react
作为对等依赖项。我发现this answer导致我添加package.json
作为对等依赖和开发依赖。进行更改后,测试可以正常进行。
这个解决方案对我来说并不是超级干净,但是我预计不会有任何问题,因此我现在将继续使用这种方法。