我正在使用react-testing-library
测试一个简单的组件,该组件内部有一个嵌套的反应路由器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.
我通过嘲笑链接解决了这个问题:
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();
});
我在Link
组件为undefined
时遇到了类似的问题。在我们的案例中,它是由现有的玩笑模仿引起的。在__mocks__/react-router-dom.js
下的代码库中有一个文件没有提供Link
的实现。因此,所有其他测试都使用了react-router-dom
模块的模拟实现。Jest使用约定对模块进行自动嘲讽。删除此模拟解决了问题