React + Antd + Electron + Jest + enzyme 前端项目测试配置踩坑

1,962 阅读1分钟

        最近做的项目需要部署前端的单元测试,因为是React项目的缘故,所以选取了与之联系甚密的Jest测试框架并结合enzyme。

        项目本身自带的框架提供了jest的测试配置,但是实测过程中遇到了问题,下面会逐一说明。

        首先在package.json中配置jest和测试的script启动脚本

  "jest": {    "testURL": "http://localhost/",
    "moduleNameMapper": {      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/internals/mocks/fileMock.js",      "\\.(css|less|sass|scss)$": "identity-obj-proxy"    },    "moduleFileExtensions": [      "js"    ],    "moduleDirectories": [      "node_modules",      "app/node_modules"    ],    "transform": {      "^.+\\.js?$": "babel-jest"    },    "transformIgnorePatterns": [      "node_modules/(?!antd)/"    ],    "setupFiles": [      "./internals/scripts/CheckBuildsExist.js"    ]  },

启动脚本:

"test": "cross-env NODE_ENV=test BABEL_ENV=node BABEL_DISABLE_CACHE=1 jest",

踩坑一:

      项目的UI框架使用了蚂蚁金服的ant-design, 在测试过程中一直提示

      ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Input from './Input';

SyntaxError: Unexpected identifier

解决办法是在package.json的jest配置中加入

"transformIgnorePatterns": [      "node_modules/(?!antd)/"    ],

踩坑二: 同样是来自antd的报错, 提示 import "./index.css"  SyntaxError: Unexpected identifier

     解决办法:将antd的按需引入的style属性设置为less, 同时在babel.config.js中做如下的配置

    env: {      node: {        plugins: [          [            'babel-plugin-transform-require-ignore',            {              extensions: ['.less', '.scss'],            },          ],        ],      },    },