1、安装 Jest 和 Vue Test Utils
npm install --save-dev jest @vue/test-utils
2、配置 package.json
// package.json
{
"scripts": {
"test": "jest"
}
}
3、需要安装和配置 vue-jest 预处理器
npm install --save-dev vue-jest
4、在package.json 中创建一个 jest 块或在项目根目录创建 jest.config.js
module.exports = {
moduleFileExtensions: [‘js‘, ‘jsx‘, ‘json‘, ‘vue‘],
transform: {
‘^.+\\.vue$‘: ‘vue-jest‘,
‘.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$‘:
‘jest-transform-stub‘,
// 为 Jest 配置 Babel
‘^.+\\.jsx?$‘: ‘babel-jest‘
},
transformIgnorePatterns: [‘/node_modules/‘],
// 别名
moduleNameMapper: {
‘^@/(.*)$‘: ‘<rootdir>/src/$1‘
},
snapshotSerializers: [‘jest-serializer-vue‘],
testMatch: [
‘**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)‘
],
testURL: ‘http://localhost/‘,
watchPlugins: [
‘jest-watch-typeahead/filename‘,
‘jest-watch-typeahead/testname‘
]
};
1、babel 解析 es6 出错,需要配置 babel 预设
> 需要配置安装 @babel/preset-env [babel-preset-env 会有问题]
npm install --save-dev @babel/preset-env
> 配置 babel.config.js
module.exports = {
presets: [
// 使可以正常运行 vue 项目,
‘@vue/app‘,
[
‘@babel/preset-env‘,
{
modules: false,
}
]
],
env: {
test: {
presets: [[‘@babel/preset-env‘, { targets: { node: ‘current‘ } }]]
}
}
}
2、npm test
> 清除缓存,然后再执行测试参考链接
原文:https://www.cnblogs.com/chentingjun/p/11752643.html