简体   繁体   English

在组件中使用 React.Children 时,Jest 和 React 测试库返回未定义的错误

[英]Jest and React Testing Library returning undefined error when using React.Children in a component

I have a component that uses React.Children internally to do some changes to the children components when rendering it.我有一个组件,它在内部使用React.Children在渲染它时对子组件进行一些更改。 When I try to test it using Jest and React Testing Library, I get the error TypeError: Cannot read properties of undefined (reading 'Children') , and it points to the line where I'm using React.Children.map .当我尝试使用 Jest 和 React 测试库对其进行测试时,我收到错误TypeError: Cannot read properties of undefined (reading 'Children') ,它指向我正在使用React.Children.map的行。

I tried to write a simple component to see if it was a problem on the more complex component, but it seems to be happening as well.我试图编写一个简单的组件,看看它是否是更复杂的组件的问题,但它似乎也在发生。 Here's the test component I created:这是我创建的测试组件:

import React from 'react';

export default function Testing({ children }) {
  return <div>{React.Children.map(children, (child) => child)}</div>;
}

And here's the test:这是测试:

import { render } from '@testing-library/react';

import Testing from './Testing';

describe('Home', () => {
  it('should render successfully', () => {
    const { baseElement } = render(<Testing>Testing</Testing>);
    expect(baseElement).toBeTruthy();
  });
});

And here's the returned error:这是返回的错误:

       detail: TypeError: Cannot read properties of undefined (reading 'Children')
          at Testing (/Users/user/projects/my-project/src/features/Home/Testing.tsx:4:22)

I tried importing React into the test to see if it would make a difference, but I doesn't.我尝试将 React 导入到测试中,看看它是否会有所作为,但我没有。 I also tried to look for this on both Jest and React Testing Library docs, but I couldn't find anything.我还尝试在 Jest 和 React 测试库文档中查找此内容,但我找不到任何东西。 I also couldn't find references to this problem on the internet, which is a bit strange as I believe I'm not the first one who's testing components that uses React.Children internally.我在互联网上也找不到对这个问题的引用,这有点奇怪,因为我相信我不是第一个在内部测试使用React.Children的组件的人。

Any help would be welcomed!欢迎任何帮助! Thanks!谢谢!

Its because children is undefined.这是因为孩子是未定义的。 Try by using React?.Children?.map(children, (child) => child) in your code尝试在您的代码中使用React?.Children?.map(children, (child) => child)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM