【问题标题】:Why does Jest fail to run tests that reference npm packages?为什么 Jest 无法运行引用 npm 包的测试?
【发布时间】: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,因为它更常用。)

标签: reactjs npm jestjs


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-15
    • 2022-01-05
    • 2019-10-21
    • 1970-01-01
    • 2020-11-25
    • 2022-08-07
    • 2021-08-08
    • 2020-05-07
    相关资源
    最近更新 更多