首页 > 解决方案 > 为什么 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 配置吗?

标签: reactjsnpmjestjs

解决方案


问题是我在文件中引用semantic-ui-react为对等依赖项。package.json我找到了这个答案,这导致我将其添加semantic-ui-react为对等依赖项和开发依赖项。进行更改后,测试工作正常。

这个解决方案对我来说不是很干净,但我预计不会有任何问题,所以我现在将采用这种方法。


推荐阅读