我正在try 为该组件编写单元测试

const HomepageVideos = ({ place, close }) => {

    return (
        <>

            <Button className="mt-2 ms-2 close" onClick={close}>Start Over</Button>
            <div className="video text-center">
                <video autoPlay muted loop className='mt-3 video' data-testid="video">
                    {place === 'Dubai-UAE' ?
                        <source src='dubai.mp4' type="video/mp4" /> :
                        place === 'Kotor-MONTENEGRO' ?
                            <source src='kotor.mp4' type="video/mp4" /> :
                            <source src='tel-aviv.mp4' type="video/mp4" />
                    }
                </video>
                <h1>{place}</h1>

                
                <Link to="/flights" state={{ place }}>
                    <Button className="bg-warning text-dark mt-2">Flights to {place}</Button>
                </Link>


            </div>

        </>
    );
}

但是,我编写的任何测试都会返回以下错误消息:

Console.error 错误:未捕获[TypeError:无法解析‘act__nampace.useContext(...)’的属性‘basename’,因为它为空.]

我认为这个错误与在组件HomepageVideos中使用<Link/>有关.不存在到该组件的特定路径,因为它是本身包括在父组件<Homepage/>中的另一组件<HomeForm/>的一部分.我已经将应用程序包装在index.js中的<Router/>中.该功能运行良好,但我似乎无法编写任何测试.我做错了什么?

推荐答案

react-router中的Link组件必须位于路由内部才能工作.您可以使用MemoryRouter测试您的组件.

const mockClose = jest.fn();
describe('tests the HomePageVideos component', () => {
  it('renders the component', async () => {
    const routes = [
      {
        path: '/test',
        element: <HomePageVideos place="Dubai-UAE" close={mockClose} />,
      },
    ];

    const router = createMemoryRouter(routes, {
      initialEntries: ['/test'],
      initialIndex: 0,
    });

    render(<RouterProvider router={router} />);

    expect(screen.getByRole('link')).toBeInTheDocument();
  });
});

Reactjs相关问答推荐

App.js中的H2组件不会动态呈现.这可能是什么问题?

基本react 应用程序正在触发两次Use Effect

在REACT-RUTER-DOMV6中使用通用页面包装组件有问题吗?

使用experial_useFormState将参数传递给服务器操作

为什么我的react 简单计时器项目不起作用?

尽管所有页面在 Reactjs 中都是公开的,但始终导航到特定页面

为 Next.js 应用程序目录中的所有页面添加逻辑的全局文件是什么?

在一个事件处理程序中进行多次调度是个好主意吗?

如何在PrimeReact的表格中修改筛选图标功能

Firebase查询返回随机用户数据,而不是过滤后的用户数据

React 测试库包装器组件

为嵌套路由配置一个不存在的 url 的重定向

来自一个自定义 React Native 组件的样式从另一个自定义组件移除样式

我刚刚部署了我的 Vite React 站点,但我的图标/图像没有部署

Storybook - 无法解析generated-stories-entry.cjs/字段browser不包含有效的别名配置

如何在 React 中单击鼠标的位置动态添加 div?

如何使用 useEffect 和 if 语句 React

如果 URL 已随功能组件更改,则取消刷新

npm init vite@latest 和 npm init vite 有什么区别?

react / firebase 基地.如何在我的项目中保存更新的数据?