Vite + Vue3 项目配置 ESLint 规范和 Jest 单元测试 - 掘金
jest、vue test utils 入门 vue3 + ts 组件测试 - 掘金
Vite+TS+Jest, 配置+踩坑记录 - 掘金
基于以上网址参考
tsconfig.json中
{
"extends": "@vue/tsconfig/tsconfig.web.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"types": ["@types/jest"]
},
"references": [
{
"path": "./tsconfig.node.json"
}
]
}
jest.config.js中
const path = require('path')
module.exports = {
rootDir: path.resolve(__dirname),
clearMocks: true,
coverageDirectory: 'coverage',
coverageProvider: 'v8',
moduleFileExtensions: ['vue', 'js', 'json', 'jsx', 'ts', 'tsx', 'node'],
// 别名设置
moduleNameMapper: {
'@/(.*)$': '/src/$1'
},
preset: 'ts-jest',
testEnvironment: 'jsdom',
// 测试文件
testMatch: ['/src/__tests__/**/*.(spec|test).(ts|tsx|js)'],
testPathIgnorePatterns: ['/node_modules/'],
moduleFileExtensions: ['js', 'json', 'ts', 'tsx'],
transform: {
'^.+\\.vue$': '@vue/vue3-jest',
'^.+\\.(ts|tsx|js|jsx)$': [
'babel-jest', {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
['@babel/preset-typescript']
],
plugins: ['@vue/babel-plugin-jsx']
}
]
}
}
在下载@vue/test-utils的时候一定要手动下载 npm i @vue/test-utils@next -D
否则会报 Vue is undefined
package.json
{
"name": "ts-jest-dome",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "run-p type-check build-only",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --noEmit",
"test": "jest"
},
"dependencies": {
"@babel/core": "^7.21.4",
"@babel/preset-env": "^7.21.4",
"@babel/preset-typescript": "^7.21.4",
"@testing-library/jest-dom": "^5.16.5",
"@types/jest": "^29.5.0",
"@vue/babel-plugin-jsx": "^1.1.1",
"@vue/test-utils": "^2.0.0-rc.18",
"@vue/vue3-jest": "^29.2.3",
"babel-jest": "29.0",
"jest": "29.0",
"jest-environment-jsdom": "^29.5.0",
"ts-jest": "^29.1.0",
"vue": "^3.2.47",
"vue-router": "^4.1.6"
},
"devDependencies": {
"@types/node": "^18.14.2",
"@vitejs/plugin-vue": "^4.0.0",
"@vue/tsconfig": "^0.1.3",
"npm-run-all": "^4.1.5",
"typescript": "~4.8.4",
"vite": "^4.1.4",
"vue-tsc": "^1.2.0"
}
}
vite.config.ts
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
tsconfig.node.json
{
"extends": "@vue/tsconfig/tsconfig.node.json",
"include": ["vite.config.*", "vitest.config.*", "cypress.config.*", "playwright.config.*"],
"compilerOptions": {
"composite": true,
"types": ["node"]
}
}
不会飘红!