React-testing-library 和 <Link> 元素类型无效:需要字符串或类/函数,但得到:未定义

Com*_*ode 8 jestjs react-router-dom react-testing-library

我正在用来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.
Run Code Online (Sandbox Code Playgroud)

Com*_*ode 8

我通过嘲笑链接解决了这个问题:

jest.mock('react-router-dom', () => ({
  Link: jest.fn().mockImplementation(({ children }) => {
    return children;
  }),
}));
Run Code Online (Sandbox Code Playgroud)

这样我就可以正常测试我的组件:

 test('render MyComponent with <Link>', async () => {
    const myListOfLinks = mockLinks();
    render(<MyComponent parents={myListOfLinks} />);
    const links = await screen.findByTestId('my-links');
    expect(MyComponent).toBeInTheDocument();
  });
Run Code Online (Sandbox Code Playgroud)