npm install --save-dev jest @vue/test-utils babel-preset-env babel-jest jest jest-serializer-vue vue-jest babel-core
babel.config.js-修改
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset',
[
'@babel/preset-env',
{
modules: false,
}
]
],
env: {
test: {
presets: [['@babel/preset-env', { targets: { node: 'current' } }]]
}
}
}
package.json文件--"scripts"新增:"test": "jest"
"jest": {
"moduleFileExtensions": [
"js",
"vue"
],
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1"
},
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
},
"snapshotSerializers": [
"<rootDir>/node_modules/jest-serializer-vue"
]
}
单元测试简单例子:名称.spec.js
import { mount } from '@vue/test-utils' import luckyGuy from '@/views/doc/stepMeter/index.vue'
test('renders correctly', () => {
const wrapper = mount(luckyGuy)
expect(wrapper.element).toMatchSnapshot()
})