我们还是先整体考虑vitest增加配置分成哪几个部分
- vscode的插件提示配置
- package.json的命令以及相关包配置
- vitest.config.js
- eslint相关配置
- vitest样例代码给出
我们按照步骤一个一个来进行配置说明
-
vscode配置
-
template\config\vitest\.vscode\extensions.json
json{ "recommendations": ["vitest.explorer"] }
-
-
package.json配置:需要有个执行vitest的script命令,以及三个包的依赖
-
template\config\vitest\package.json
perl{ "scripts": { "test:unit": "vitest" }, "devDependencies": { "@vue/test-utils": "^2.4.6", "jsdom": "^26.1.0", "vitest": "^3.2.4" } }
-
-
vitest.config.js配置:
template\config\vitest\vitest.config.js
:Vitest 的主要优势之一是它与 Vite 的统一配置,见官方说明- 这里的exclude,vitest/config中有帮我们导出许多默认配置我们可以直接使用,可以减少我们配置排除文件的心智
- root是我们的项目的根目录,见说明
javascriptimport { fileURLToPath } from 'node:url' import { mergeConfig, defineConfig, configDefaults } from 'vitest/config' import viteConfig from './vite.config' export default mergeConfig( viteConfig, defineConfig({ test: { environment: 'jsdom', exclude: [ ...configDefaults.exclude, // 'e2e/**', // 项目暂时没有引入e2e配置所以这里先暂时注释 ], root: fileURLToPath(new URL('./', import.meta.url)), }, }), )
- 这里的exclude,vitest/config中有帮我们导出许多默认配置我们可以直接使用,可以减少我们配置排除文件的心智
-
eslint配置:需要使用vitest的eslint插件,如下配置一下推荐配置已经作用的文件就好
-
template\eslint\vitest\package.json
perl{ "devDependencies": { "@vitest/eslint-plugin": "^1.2.7" } }
-
template\eslint\vitest\eslint.config.js.data.mjs
javascriptexport default function getData({ oldData }) { const pluginVitestImporter = { id: 'pluginVitest', importer: "import pluginVitest from '@vitest/eslint-plugin'", } const pluginVitestConfig = { id: 'pluginVitest', config: "{ ...pluginVitest.configs.recommended, files: ['src/**/__tests__/*'], },", } oldData.importerList.push(pluginVitestImporter) oldData.configList.push(pluginVitestConfig) return oldData }
-
-
样例代码。可以放在code目录下,但是因为给出来一个就好,不会有其他增加,所以我们干脆集中放在
template\config\vitest
下面。相关代码语法请见官方文档,我们这里就是判定HelloWorld组件中是否有hello world
字符-
template\config\vitest\src\components\__tests__\HelloWorld.spec.js
javascriptimport { describe, it, expect } from 'vitest' import { mount } from '@vue/test-utils' import HelloWorld from '../HelloWorld.vue' describe('HelloWorld', () => { it('renders properly', () => { const wrapper = mount(HelloWorld) expect(wrapper.text()).toContain('hello world') }) })
-
对应的index.ts我们需要做出相应渲染逻辑的改动,需要注意解决prettier和eslint冲突的插件需要放在最后
scss
const create = async (name: string, options: Options) => {
...
// 添加对应的配置
...
if (needsVitest) {
render('config/vitest')
}
if (needsEslint) {
render('config/eslint')
render('eslint/base') // eslint基础配置
if (needsTypeScript) {
render('eslint/typescript')
}
if (needsVitest) {
render('eslint/vitest')
}
// 需要注意解决prettier和eslint冲突的插件需要放在最后
if (needsPrettier) {
render('eslint/prettier')
}
}
...
}