使用Preact+Vite时单元测试报错:Cannot read property '__H' of undefined
Preact + Vite 单元测试报错:TypeError: Cannot read property '__H' of undefined
问题场景
组件在浏览器中正常渲染,但执行单元测试时抛出以下错误:
name: "TypeError"
message: "Cannot read property '__H' of undefined"
组件代码片段:
export const component = (props) => { const allItems = props.options; const [totalCost, setTotalCost] = useState(0); const [checkedState, setCheckedState] = useState( new Array(allItems.length).fill(false) ); // ... }
测试文件导入语句:
import { component } from '../../../Component';
可能原因及解决步骤
1. 未正确导入Preact的React Hooks
确保组件中的useState是从preact包导入,而非react:
// 正确写法 import { useState } from 'preact'; // 错误写法(会导致测试环境混淆React和Preact) // import { useState } from 'react';
2. 测试环境未配置Preact与React的兼容映射
测试框架(如Vitest/Jest)需要将react/react-dom的导入映射到preact/compat,避免测试工具默认使用React的运行时。
Vitest 配置示例(vite.config.test.js):
import { defineConfig } from 'vitest/config'; import preact from '@preact/preset-vite'; export default defineConfig({ plugins: [preact()], resolve: { alias: { 'react': 'preact/compat', 'react-dom': 'preact/compat' } } });
Jest 配置示例(jest.config.js):
module.exports = { moduleNameMapper: { '^react$': 'preact/compat', '^react-dom$': 'preact/compat' }, testEnvironment: 'jsdom' };
3. 使用了React的测试库而非Preact版本
确保测试时使用@testing-library/preact来渲染组件,而非@testing-library/react:
// 正确写法 import { render } from '@testing-library/preact'; // 错误写法 // import { render } from '@testing-library/react';
4. 测试时未传入必要的Props
组件中直接使用props.options.length,如果测试渲染时未传入options,会导致allItems为undefined,进而引发后续渲染错误(间接导致__H相关报错)。测试时必须传入合法的options参数:
// 测试渲染时传入空数组或测试数据 render(<component options={[]} />);
内容的提问来源于stack exchange,提问作者Swaraj Ghosh
相关产品推荐
相关产品推荐

