javascript - 错误: Uncaught [TypeError: Cannot read property 'x' of undefined Jest react testing

标签 javascript reactjs ts-jest

我是 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/

相关文章:

javascript - Coffeescript splats 和 Angular 的注入(inject)

javascript - 在 javascript 中阻止 "wait"函数?

reactjs - 将 publicPath 添加到 Storybook React

javascript - 确定 JavaScript Dropbox Datastore API 何时完成插入

javascript - React.js 子组件不更新从 props 派生的样式,为什么? (样式组件)

javascript - 映射 csv 以在 React 中显示数组中的每个项目

typescript - 缺少 TS-Jest 实用程序

typescript - Jest mock 总是给出 undefined (typescript + ts-jest)

reactjs - React Jest 测试无法使用 ts-jest 运行 - 导入文件上出现意外标记

javascript - 单击 javascript 按钮时添加媒体