我是 react 和测试的新手,所以也许我误解了文档,但我有一个定义 const 变量的函数,它只是一个具有属性“X”的对象数组,我们称之为。我过滤这个数组并获取第一个对象并查找 X。
然后,我将其导入到我的笑话测试文件中,但在运行测试时失败,并显示错误:未捕获[TypeError:无法读取未定义的属性“X”].
我不确定为什么,因为当我实际运行应用程序时它可以工作,所以我假设需要进行某种变量模拟?
下面是我的代码。我已经把不重要的部分去掉了。如果有人可以引导我走向正确的方向。
main.jsx
export default function main({
name, value, options, onChange, onBlur, inputRef, error, complete
}) {
const data = options.filter(name => name.uuid === value)[0].X.slice(8);
return ( blah blah blah, this works when I actually render it )
测试.jsx
import main from './main';
test('Renders', () => {
const options = [
{
uuid: 'foo',
X: ['a', 'b']
}
]
const { getByText } = render(
<main
name="test"
value=""
options={options}
onChange={() => {}}
onBlur={() => {}}
/>
);
});
最佳答案
因为您传递的 props value
是“”,所以 options.filter(name => name.uuid === value)[0]
未定义。您可以更新值
来修复
value="foo"
关于javascript - 错误: Uncaught [TypeError: Cannot read property 'x' of undefined Jest react testing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68326395/