【问题标题】:Cannot find module 'enzyme' from 'setupTests.ts'无法从“setupTests.ts”中找到模块“酶”
【发布时间】:2019-03-27 06:42:40
【问题描述】:

我想使用酶在我的 React 项目中使用 TypeScript 执行单元测试。

我使用了有关向 create-react-app 添加测试的文档 - runnning tests

我在 /src 中创建了 setupTests.ts 文件

setupTests.ts

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

我写了一个测试

App.test.ts

import React from 'react';
import { shallow } from 'enzyme';
import App from './App';

it('renders without crashing', () => {
  shallow(<App />);
});

如果我在 setupTests.ts 中注释配置适配器的行,则使用 react-dom 的测试可以正常工作

setupTests.ts

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

// configure({ adapter: new Adapter() });

App.test.ts

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Dashboard';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});

package.json

{
  "name": "sampleapp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^3.9.2",
    "@material-ui/icons": "^3.0.2",
    "@types/enzyme": "^3.9.1",
    "@types/enzyme-adapter-react-16": "^1.0.5",
    "@types/enzyme-to-json": "^1.5.3",
    "@types/jest": "24.0.11",
    "@types/node": "11.12.0",
    "@types/react": "16.8.8",
    "@types/react-dom": "16.8.3",
    "@types/react-redux": "^7.0.5",
    "@types/react-router-dom": "^4.3.1",
    "@types/redux-thunk": "^2.1.0",
    "axios": "^0.18.0",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-redux": "^6.0.1",
    "react-router-dom": "^5.0.0",
    "react-scripts": "2.1.8",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0",
    "typescript": "3.3.4000"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

测试应该成功运行。但它失败并给我一个错误

Cannot find module 'enzyme' from 'setupTests.ts'

【问题讨论】:

  • 好像没有装酶
  • @Boy With Silver Wings I have.. 它安装为@types/enzyme,就像我使用打字稿一样。
  • @Sruthi @types/enzyme 仅用于 typescript 接口等。
  • 只需按照您链接到的docs 所述安装所有库。 @types 只是打字

标签: reactjs typescript unit-testing enzyme


【解决方案1】:

你应该这样做yarn add enzyme,你会很好的! 或者 npm i enzyme 如果您使用的是 npm。

@types/enzyme 用于获取 typescript 接口,但不是实际的酶包!

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 2020-06-05
    • 2020-06-22
    • 2018-07-31
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2012-02-27
    相关资源
    最近更新 更多