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

Viewed 32

I have a component that uses React.Children internally to do some changes to the children components when rendering it. 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.

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. I also tried to look for this on both Jest and React Testing Library docs, but I couldn't find anything. 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.

Any help would be welcomed! Thanks!

1 Answers

Its because children is undefined. Try by using React?.Children?.map(children, (child) => child)in your code

Related