反应测试库和<Link>元素类型无效:需要字符串或类/函数,但得到:未定义



我正在使用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使用约定对模块进行自动嘲讽。删除此模拟解决了问题

最新更新