Hello friends 🙏, today someone came to me with this issue, it was a React v16 project and facing issue while trying to match the snapshots using React Testing Library.
TypeError: parentInstance.children.indexOf is not a function
This error was pointing to .create method of the renderer:
import renderer from 'react-test-renderer';
.
.
.
const component = renderer.create(<MyComponent/>);
expect(component).toMatchSnapshot();
So after bit some research 🔍😅, found that error is happening due to some compatibility issues with the react-test-renderer and createPortal of React.
Basically issue is using react-test-renderer to create a snapshot of a component, which contain React createPortal function. ReactDOM.createPortal is not supported inside a React TestRenderer tree.
Another renderer can’t be used in addition to the test renderer.
And in our scenario <MyComponent/> is using React createPortal method and in this case parentInstance.children is an instance of HTMLCollection, but test-renderer expects an array of Instance type.
And after doing some research again 🔍😅, found that as a workaround we can use toJson method from enzyme-to-json to match the snapshot.
import renderer from 'react-test-renderer';
import toJson from 'enzyme-to-json';
.
.
.
const component = toJson(renderer.create(<MyComponent/>));
expect(component).toMatchSnapshot();
Do you know anyother way to resolve this issue, feel free to comment.
Thanks 🙏.