项目背景
时间:2022
技术选型:基于vite2+vue2+element+ts的单页面web app(node:12+、 vue:2.6.12 、vuex:3.5.1 、 vite:2.1.5、ts:3.9.6、elementui2.15.7、vue-demi0.12.1)
不要问我当时怎么想的,我脑子进了水,粗略的以为自己做了一次伟大变革,想为组内做一个vue3 ts过渡期的项目,允许vue2,也允许vue3的写法; vitest需要vite4,当前升级会导致项目无辜启动失败,故而决定用jest
准备单元测试 1、npm install --save-dev jest@27 @types/jest ts-jest@27 vue-jest @vue/test-utils
2、配置Jest
//jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
transform: {
'^.+\\.vue$': 'vue-jest',
'^.+\\.(ts|tsx)?$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'js', 'vue', 'json'],
transformIgnorePatterns: [
"/node_modules/(?!@babel/runtime)",
],
}
3、安装 vue-jest
为了让Jest能够处理Vue文件,需要安装‘vue-jest’
npm install vue-jest@next --save-dev
4、安装babel类保证Jest能正确处理ES模块
npm install @babel/core @babel/preset-env babel-jest --save-dev
.babelrc中添加设置
{
"presets": ["@babel/preset-env"]
}
5、配置ts,确保‘tsconfig.json’文件中包含对Jest的类型定义
{
"compilerOptions": {
"types": ["jest"],
// 其他 TypeScript 配置
}
}
6、创建测试文件 可以创建一个tests目录,创建一个示例测试文件,例如,‘example.spec.ts’
import { mount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message'
const wrapper = mount(HelloWorld, {
propsData: { msg }
})
expect(wrapper.text()).toMatch(msg)
})
})
7、在‘package.json’中添加测试脚本
"scripts": {
"jest": "jest"
}
7、运行测试
npm run jest
以上就是vite2项目中使用vue2.6和ts,安装jest进行单元测试的完整步骤
项目的实际变化
单测的结果
简单记录下