【发布时间】: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