我正在使用react-testing-library
测试其中包含嵌套的react-router-dom的<Link>
的简单组件,并且出现此错误:
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.
答案 0 :(得分:1)
我通过模拟链接解决了该问题:
jest.mock('react-router-dom', () => ({
Link: jest.fn().mockImplementation(({ children }) => {
return children;
}),
}));
这样,我就可以正常测试我的组件了:
test('render MyComponent with <Link>', async () => {
const myListOfLinks = mockLinks();
render(<MyComponent parents={myListOfLinks} />);
const links = await screen.findByTestId('my-links');
expect(MyComponent).toBeInTheDocument();
});
答案 1 :(得分:0)
我在 Link
组件为 undefined
时遇到了类似的问题。在我们的例子中,它是由现有的玩笑模拟引起的。在我们的代码库中 __mocks__/react-router-dom.js
下有一个文件,它没有提供 Link
的实现。所以所有其他测试都使用 react-router-dom
模块的模拟实现。 Jest 使用 convention 自动模拟模块。删除这个模拟解决了这个问题