Home > Software engineering >  react test shows wrong result
react test shows wrong result

Time:12-13

hi i am using test case for first time i have written a test case for breadcrumb component but its showing a test case failed: i am getting the result in brower but its shows fail while test case can anyone help me with it its the first time i am writting test case

 FAIL  src/component/__test__/breadcrumb.test.js (20.411 s)
  × renders breadcrumbs correctly (786 ms)
                                                                                                                         
  ● renders breadcrumbs correctly                                                                                        
                                                                                                                         
    useNavigate() may be used only in the context of a <Router> component.

this is my code for Breadcrumb component:

import React from "react";
import {
  Breadcrumbs as MUIBreadcrumbs,
  Link,
  Typography,
} from "@material-ui/core";
import { useNavigate, useLocation } from "react-router-dom";
const Breadcrumbs = () => {
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const pathnames = pathname.split("/").filter(Boolean);
  return (
    <MUIBreadcrumbs aria-label="breadcrumb">
      {pathnames.length ? (
        <Link onClick={() => navigate("/")}>Dashboard</Link>
      ) : (
        <Typography> Dashboard </Typography>
      )}
      {pathnames.map((name, index) => {
        const routeTo = `/${pathnames.slice(0, index   1).join("/")}`;
        const isLast = index === pathnames.length - 1;
        return isLast ? (
          <Typography key={name}>{name}</Typography>
        ) : (
          <Link key={name} onClick={() => navigate(routeTo)}>
            {name}
          </Link>
        );
      })}
    </MUIBreadcrumbs>
  );
};

export default Breadcrumbs;

and this is the test case i have written:

import React from 'react';
import { render, screen } from '@testing-library/react';
import Breadcrumbs from '../breadcrumb/Breadcrumb';


test('renders breadcrumbs correctly', () => {
  const items = [
    {
      label: 'Dashboard',
      link: '/'
    },
    {
      label: 'Employee',
      link: '/employee'
    }
  ];

  render(<Breadcrumbs items={items} />);

  // Verify that the breadcrumbs are rendered
  expect(screen.getByText('Dashboard')).toBeInTheDocument();
  expect(screen.getByText('Employee')).toBeInTheDocument();

  // Verify that the links are correct
  expect(screen.getByText('Dashboard')).toHaveAttribute('href', '/');
  expect(screen.getByText('Employee')).toHaveAttribute('href', '/employee');
});

CodePudding user response:

As the error message suggests, useNavigate is a hook and can only be used in context or <Router> component.

useNavigate hook makes use of the context that the Router component provides, so so your component has to be nested inside of a Router.

  • Related