Astro 5.0.2结合Vitest:getViteConfig与容器renderToString失效问题
Astro 5.0.2 + Vitest 2.1.8 测试配置问题解决思路
1. 解决getViteConfig中test字段的类型提示问题
Astro的getViteConfig返回的Vite配置类型默认不包含Vitest的test字段,导致语法高亮提示不存在。可以通过类型断言扩展配置类型,修改vitest.config.ts:
/// <reference types="vitest/config" /> import type { UserConfig } from 'vite'; import { getViteConfig } from 'astro/config'; export default getViteConfig({ test: { include: ['./tests/*.{test,spec}.?(c|m)[jt]s?(x)'], reporters: [ 'default', ['junit', { suiteName: 'UI tests' }] ], environment: 'jsdom', // 关键:添加DOM测试环境 } } as UserConfig);
2. 修复测试运行时的未处理错误
出现Vitest caught 2 unhandled errors的核心原因是缺少DOM测试环境,Astro组件渲染依赖DOM API,需要在Vitest配置中启用jsdom环境(上述配置已添加)。同时确保安装jsdom依赖:
npm install jsdom --save-dev
若错误仍存在,可在测试文件顶部添加环境初始化代码:
import { beforeAll } from 'vitest'; beforeAll(() => { globalThis.Astro = { props: {} }; });
3. 改用defineConfig时的语法解析错误解决
直接使用Vitest的defineConfig时,Vite无法识别.astro文件的特殊语法(Frontmatter、组件模板),必须添加Astro的Vite插件。修改vitest.config.ts如下:
/// <reference types="vitest/config" /> import { defineConfig } from 'vitest/config'; import astro from '@astrojs/vite-plugin-astro'; export default defineConfig({ plugins: [astro()], // 关键:添加Astro插件处理.astro文件 test: { include: ['./tests/*.{test,spec}.?(c|m)[jt]s?(x)'], reporters: ['default', ['junit', { suiteName: 'UI tests' }]], environment: 'jsdom', }, });
4. 测试代码优化建议
确保experimental_AstroContainer的使用符合Astro 5.x要求,同时补充断言验证渲染结果:
import { experimental_AstroContainer as AstroContainer } from 'astro/container'; import { expect, test } from 'vitest'; import Card from '../src/components/Card.astro'; test('Card renders props correctly', async () => { const container = await AstroContainer.create(); const result = await container.renderToString(Card, { props: { title: "Title", date: "20 Aug 2024" } }); expect(result).toContain('<h1>Title</h1>'); expect(result).toContain('<p>20 Aug 2024</p>'); });
内容的提问来源于stack exchange,提问作者thomi
相关产品推荐
相关产品推荐

