vue-test-utils官网:https://vue-test-utils.vuejs.org/zh/
jest官网:https://jestjs.io
依赖包
请安装它们👇
yarn add @vue/test-utils vue-jest
yarn jestjest-serializer-vue
yarn add babel-jest babel-core@^7.0.0-bridge.0⚠️:vue-jest依赖与babel-core。我们的环境现在都是babel7,通过npm安装的babel-core默认的还是6版本,所以要指定babel-core安装的系列为7,否则会出现解析问题。
配置
jest配置:告诉jest它需要哪些额外的配置
jest相关的配置可以配置在package.json中或者单独的jest.config.json文件中:
// jest.config.json
{
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
"^.+.js$": "<rootDir>/node_modules/babel-jest", // jest使用babel解析js
".*.(vue)$": "<rootDir>/node_modules/vue-jest" // jest对vue单文件的解析
},
"snapshotSerializers": [
"<rootDir>/node_modules/jest-serializer-vue"
],
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1", //为了解析webpack配置的alias字段
"^tim-architect/(.*)$": "<rootDir>/tim-architect/$1"
},
"transformIgnorePatterns": [
"node_modules/(?!(yourModuleName))"
]}
⚠️:transformIgnorePatterns的默认配置是[“node_modules”],表示所有的node_modules下的包都不需要babel解析。但是一些3rd库提供的文件仍然是未编译的es6语法,jest在解析时会报语法错误。因此需要指定白名单,需要那些node_modules下的包被babel转换。
babel配置:告诉babel你需要用哪些工具去处理一坨(💩香么 ?💩 : 💩 )代码
推荐使用babel.config.js(babel需要转换的node_modules同样生效)而不是.babelrc(当前项目生效)。
{
...,
env: {
test: {
presets: [[
'@babel/env',
{
modules: 'auto', // 现在不能通过webpack来解析s6 module,需要使用babel来解析,所以要开启
targets: {
node: 'current' // 指定环境为当前node版本,减少解析不识别语法的范围
}
}
]],
plugins: [[
'@babel/plugin-transform-runtime', {
corejs: 2,
useESModules: false // 不允许使用es modules,babel需要通过@babel/plugin-transform-modules-commonjs将es module转换为commonjs模块解析
}
] ] }
}
}
⚠️:通过babel的env.test指定jest测试时需要的babel配置(同webpack转换解析时不同),jest会自动识别env.test的配置。
单测文件
理解:










