I'm using react-testing-library to test a simple component which has a nested react-router-dom's <Link> inside of it and I am getting this error:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I solved it by mocking the Link:
jest.mock('react-router-dom', () => ({
Link: jest.fn().mockImplementation(({ children }) => {
return children;
}),
}));
That way I can test my component normally:
test('render MyComponent with <Link>', async () => {
const myListOfLinks = mockLinks();
render(<MyComponent parents={myListOfLinks} />);
const links = await screen.findByTestId('my-links');
expect(MyComponent).toBeInTheDocument();
});
I had similar issue with Link component being undefined. In our case it was caused by existing jest mock. There was a file in our codebase under __mocks__/react-router-dom.js which didn't provide an implementation for Link. So all other tests were using mocked implmentation of react-router-dom module. Jest uses convention for automatic mocking of modules. Removing this mock solved the issue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With