React-testing-library 和 <Link> 元素类型无效:应为字符串或 class/function 但得到:未定义
React-testing-library and <Link> Element type is invalid: expected a string or a class/function but got: undefined
我正在使用 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.
我通过模拟Link解决了它:
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 来自动模拟模块。删除这个模拟解决了问题
我正在使用 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.
我通过模拟Link解决了它:
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 来自动模拟模块。删除这个模拟解决了问题