Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-testing-library and <Link> Element type is invalid: expected a string or a class/function but got: undefined

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.
like image 355
CommonSenseCode Avatar asked Jun 21 '26 18:06

CommonSenseCode


2 Answers

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();
  });
like image 96
CommonSenseCode Avatar answered Jun 23 '26 18:06

CommonSenseCode


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

like image 25
fatbeard Avatar answered Jun 23 '26 18:06

fatbeard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!