如何解决React-testing-library和<Link>元素类型无效:预期为字符串或类/函数,但得到:未定义
我正在使用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.
解决方法
我通过模拟链接解决了该问题:
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 使用 convention 自动模拟模块。删除这个模拟解决了这个问题
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。