如何使用Vitest测试Svelte组件的Props?
如何用Vitest测试Svelte组件的Props?
问题场景
我想用Vitest测试Svelte组件的Props,组件代码如下:
<script> export let foo </script> <div>{foo}</div>
测试代码:
const { component } = render(MyComponent, { foo: 'bar' }) expect(component.foo).toBe('bar')
运行测试时触发错误:
Props cannot be read directly from the component instance
unless compiling with 'accessors: true' or '<svelte:options accessors/>'
尝试给render()传入accessors: true后问题依旧:
const { component } = render(MyComponent, { accessors: true })
解决方法
方法1:在组件内启用accessors
直接在组件中添加<svelte:options accessors/>,让组件实例生成props的访问器:
<script> export let foo </script> <svelte:options accessors/> <div>{foo}</div>
修改后即可在测试中正常读取component.foo。
方法2:全局配置Svelte编译选项
如果需要给所有组件开启accessors,可在svelte.config.js中全局设置编译选项:
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte' export default { preprocess: vitePreprocess(), compilerOptions: { accessors: true } }
此配置会让所有组件自动生成props访问器,无需逐个修改组件。
方法3:测试渲染输出(更推荐)
组件测试的核心是验证用户能看到的内容是否符合预期,无需直接读取组件实例的props。可以通过检查渲染后的文本内容来验证props是否生效:
const { getByText } = render(MyComponent, { foo: 'bar' }) expect(getByText('bar')).toBeInTheDocument()
这种方式更贴近实际使用场景,也不需要额外配置accessors。
内容的提问来源于stack exchange,提问作者Yulian
相关产品推荐
相关产品推荐

