vue3中单元测试主要是通过脚手架@vue/cli-plugin-unit-jest进行一些列配置的。现简单罗列出整个过程。(新项目通过vue create 创建时直接加入单元测试即可,vite另外探索)
第一步:导入对应的包,并添加运行指令(注意版本依赖关系)
// 导入
npm i @vue/cli-plugin-unit-jest @vue/test-utils babel-jest@27.0.6 -D
// 创建指令并运行
"test": "vue-cli-service test:unit"
第二步:运行时会提示如下报错,我们需要去添加预设解析
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration
我们在根目录下添加jest配置文件(jest.config.js),然后添加如下内容来处理解析报错问题
module.exports = {
preset:'@vue/cli-plugin-unit-jest/presets/typescript'
}
首先,安装解析包@vue/vue3-jest,出现报错是我们版本不对,我们根据提示安装对应的版本即可
npm i @vue/vue3-jest@^27.0.0-alpha.3 -D
其次,安装jest包
npm i jest@27.1.0 -D
最后,安装解析包ts-jest
npm i @types/jest@27.0.4 ts-jest@27.0.4 -D
第三步:我们在跟目录下创建单元测试文件,测试文件放在tests文件夹下,命名以.spec.ts结尾
第四步:运行指令
npm run test
这时,控制台会出现ts报错问题,我们需要在ts配置文件添加jest文件类型检测即可,如下所示
"compilerOptions": {
"types": [
"jest"
]
}
成功运行后结果显示如下