环境配置 jest + enzyme
1.下载依赖包: npm i -D jest enzyme babel-jest;
2.自定义配置jest: jest.config.js
module.exports = {
modulePaths: ['<rootDir>/src/'],
moduleNameMapper: {
'^lodash-es$':'lodash',
'\\(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/styleMock.js',
'\\.(less|css)$':'/__mocks__/styleMock.js'
},
collectCoverage:true,
coverageDirectory:'<rootDir>/src/',
coveragePathIgnorePatterns: ['<rootDir>/\\*\\*/__test__/'],
coverageReporters: ['text'],
transform: {'^.+\\.js$':'babel-jest'}
};
styleMock.js
module.exports = {};
3. .babelrc
实际项目中由于webpack可以编译es6的模块,一般将babel中设为{ "modules": false }, 如果不对测试环境进行配置的话 可能会报如下错误
解决方案:
1⃣️package.json
"scripts": { "test": "export NODE_ENV=test && jest", }
2⃣️.babelrc
{
..............
"env": {
"test": {
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
}
}
Q1: 报如下错误
Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions.
A:项目同时使用了babel6、babel7,不兼容【babel升级】
Q2:报如下错误,unexpected identifier
A:参考环境配置第三项
Q3.报如下错误, Jest encountered on unexpected token
A:webpack config doesn't transform node_modules using Babel,提示信息给出了三种解决方案。
目前解决方案是修改引用模块映射,参考环境配置第二项:
Q4.eslint 报如下错误, parsing error: using the export keyword between a decorator and a clas is not allowed.
A: 修改eslint 配置