从零搭建前端开发环境(一)——React篇:2.jest+enzyme单测和eslint

注:正像该系列(零)《扩展篇》里提到的,单测和eslint并非必须,但是对于项目的管理还是有必要引入的。

1、安装单测和eslint的依赖

eslint的安装跟从零搭建前端开发环境(零)——扩展篇:4.eslint统一代码规范里面的差不多(如果看不懂本文的一些上下文,请先看这篇),不过我们这回用的是eslint-config-airbnb,查看依赖和分版本安装具体步骤就不说了 直接上结果安装。

$ npm i -D jest babel-jest enzyme-adapter-react-16 enzyme eslint-config-airbnb [email protected] [email protected] [email protected] [email protected] eslint-loader

2、配置react的eslint

.eslintrc.js

const path = require('path');
const root = __dirname;

module.exports = {
  root: true,
  extends: 'airbnb',
  parserOptions: {
    ecmaVersion: 2017, // ES8
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
      // 启用对实验性的 object rest/spread properties 支持。该语法在 ecmaVersion: 2018 中得到支持。该选项在未来将被移除。
      experimentalObjectRestSpread: true
    }
  },
  env: {
    browser: true,
    node: true,
    jest: true
  },
  settings: {
    'import/resolver': {
      webpack: {
        config: path.resolve(root, 'config/webpack.base.js')
      }
    }
  },
  rules: {
    'max-len': 0,
    'jsx-a11y/anchor-is-valid': [ 'error', {'components': []}], // react-router <Link />
    'react/prop-types': ['error', { ignore: ['match']}] // react-router props.match
  }
}

本来打算把redux和react-router另起一篇写的,但是在配置方面实在就这么点东西,rules里面的规则就是适配react-router4的,另外我把每行100字符以内的限制也给关掉了,大家根据自己的需求来设置吧。另外还需添加.eslintignore,修改webpack.base.js,详见从零搭建前端开发环境(零)——扩展篇:4.eslint统一代码规范。来感受史上最严格规范的恐怖吧~~

3、jest + enzyme用例

细节可参考用jest构建react项目的测试框架——安装与配置和,此处会有些许不一样的地方,领会精神即可。把jest的配置和test下面的配置文件列出来,用例就不贴上来了。

config/jest.config.js

const path = require('path');

module.exports = {
  rootDir: path.resolve(__dirname, '../'),
  collectCoverage: true, // 是否收集测试时的覆盖率信息
  collectCoverageFrom: ['<rootDir>/src/**/*.{js,jsx,mjs}'], // 哪些文件需要收集覆盖率信息
  coverageDirectory: '<rootDir>/test/coverage', // 输出覆盖信息文件的目录
  coveragePathIgnorePatterns: ['/node_modules/', '<rootDir>/src/index.jsx'], // 统计覆盖信息时需要忽略的文件
  moduleNameMapper: { // 主要用于与webpack的resolve.alias匹配,注意正则写法
    '^src/(.*)$': '<rootDir>/src/$1',
    '^util/(.*)$': '<rootDir>/src/util/$1',
    '^assets/(.*)$': '<rootDir>/src/assets/$1',
    '^components/(.*)$': '<rootDir>/src/components/$1',
  },
  setupFiles: ['<rootDir>/test/setup.js'], // 运行测试前可运行的脚本,比如注册enzyme的兼容
  testMatch: [ // 匹配的测试文件
    '<rootDir>/test/**/?(*.)(spec|test).{js,jsx,mjs}',
    '<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}',
  ],
  testURL: 'about:blank', // 运行环境下的url
  transform: {
    '^.+\\.(js|jsx|mjs)$': '<rootDir>/node_modules/babel-jest',
    '^.+\\.(css|less)$': '<rootDir>/test/cssTransform.js',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/test/fileTransform.js',
  },
  transformIgnorePatterns: [ // 转换时需要忽略的文件
    '[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$',
  ],
};

test/cssTransform.js

module.exports = {
  process() {
    return 'module.exports = {};';
  },
  getCacheKey() {
    // The output is always the same.
    return 'cssTransform';
  },
};

test/fileTransform.js

const path = require('path');  
  
// This is a custom Jest transformer turning file imports into filenames.  
// http://facebook.github.io/jest/docs/en/webpack.html  
  
module.exports = {  
  process(src, filename) {  
    return `module.exports = ${JSON.stringify(path.basename(filename))};`;  
  },  
};  

test/setup.js

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

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

.babelrc

{    
  "presets": [    
    ["env",{ "modules": false }],    
    "stage-2",
    "react"
  ],  
  "env": {  
    "test": {  
      "presets": ["env", "stage-2", "react"]  
    }  
  }  
}   

猜你喜欢

转载自blog.csdn.net/zhaolandelong/article/details/79813211
今日推荐