使用TypeScript在React中编写单元测试时,无法从``setupTests.ts''错误中找到模块``酶''

时间:2019-03-27 06:42:41

标签: reactjs typescript unit-testing enzyme

我想使用酶在使用打字稿的反应项目中进行单元测试。

我使用了有关向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'

1 个答案:

答案 0 :(得分:2)

您应该做yarn add enzyme,那样您会很好! 如果您使用的是npm,则为npm i enzyme

@types/enzyme用于获取打字稿界面,而不是实际的酶包!