8

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.

2 Answers 2

7

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();
  });
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.