其实参考官方文档很容易就完成搭建了,所以本文也是对官网进行一个测试搭建过程的简单演练。
https://jestjs.io/
https://enzymejs.github.io/en...javascript
固然为了方便开发,安装对应的types颇有必要css
enzyme-adapter-react官网上目前的版本列表,其它版本请移步官网查询
表格1-1java
enzyme适配器版本 | React版本 |
---|---|
enzyme-adapter-react-16 | ^16.4.0-0 |
enzyme-adapter-react-16.3 | ~16.3.0-0 |
enzyme-adapter-react-16.2 | ~16.2 |
enzyme-adapter-react-16.1 | ~16.0.0-0~16.1 |
enzyme-adapter-react-15 | ^15.5.0 |
enzyme-adapter-react-15.4 | 15.0.0-0 - 15.4.x |
enzyme-adapter-react-14 | ^0.14.0 |
enzyme-adapter-react-13 | ^0.13.0 |
.babelrcnode
{ "presets": [ [ "@babel/preset-env", { "targets": { "node": "current" } } ], "@babel/preset-typescript", "@babel/preset-react" ] }
jest.config.jsreact
module.exports = { testEnvironment: 'node', roots: ['<rootDir>'], // 测试文件是src目录下*.test.jsx或者*.test.tsx的文件 testRegex: 'src/(.+)\\.test\\.(jsx?|tsx?)$', // 自定义转换方式,转换jsx、tsx文件 transform: { '^.+\\.(j|t)sx?$': '<rootDir>/node_modules/babel-jest', }, // 模块资源映射,例如alias的配置 moduleNameMapper: { // 用于css、js、图片等文件的mock '\\.(css|less|scss)$': 'identity-obj-proxy', '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': 'identity-obj-proxy', // alias '^@mock/(.*)$': '<rootDir>/mock/$1', }, testPathIgnorePatterns: ['\\node_modules\\'], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], // 覆盖率从哪些文件收集,设置后即便0覆盖率的文件也会计算进来 collectCoverageFrom: ['src/**/*.{ts,tsx,js,jsx}', '!**/node_modules/**', '!**/dist/**'], // 测试报告输出地址 coverageDirectory: '<rootDir>/coverage', // 在每一个测试文件执行以前,运行一些代码以配置或设置测试框架。 setupFilesAfterEnv: ['./src/test/setupTests.js'], };
setupTests.jsgit
import { configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import jsdom from 'jsdom'; // 设置react和enzyme的适配器 configure({ adapter: new Adapter() }); // 配置给render挂载在global用到的dom对象 const { JSDOM } = jsdom; const { window } = new JSDOM(''); const { document } = new JSDOM(``).window; global.document = document; global.window = window;
package.jsongithub
"scripts": { ... "test": "jest" "test:coverage": "jest --coverage" }
npm run test
便可运行全部的单元测试npm run test:coverage
就能够运行生成覆盖率报告的单元测试web
测试一个checkbox组件typescript
import { mount, ReactWrapper } from 'enzyme'; import CheckBox, { Props } from './index'; import React from 'react'; describe('CheckBox', () => { ... it('should emit onChange corretly', () => { const props: Props = { checked: false, option: { label: 'test1', value: '111' }, onChange: jest.fn(), }; const wrapper = mount(<CheckBox {...props}></CheckBox>); wrapper.find('.checkbox-item').simulate('click'); expect(onChange).toHaveBeenCalledWith({ checked: true, option }); }); });
在开发过程当中,咱们可能只想运行一个测试case,有2个方案能够解决npm
修改jest.config.js(不要提交到线上)
module.exports = { ... // 修改成指定文件 testRegex: 'src/(.+)\\checkbox\\.test\\.(jsx?|tsx?)$',