1

I have upgraded the react router to v6 and convert all our elements to enter image description here

Which is returning the SecureRoute

  }
  return hasPermission() ? <Route {...routeProps} /> : <Route {...routeProps} element={accessForbiddenComponent} />;
};

export default SecureRoute;

And the test case as below

describe("SecureRoute", () => {
  let mockUseAuthState: jest.SpyInstance;
  let mockUseAuthorize: jest.SpyInstance;

  beforeEach(() => {
    mockUseAuthState = jest.spyOn(SecurityModule, "useAuthState");
    mockUseAuthorize = jest.spyOn(UseAuthorizeModule, "useAuthorize");
  });

  it("should show page if user is logged in", () => {
    mockUseAuthState.mockReturnValue(mockAuthState());
    mockUseAuthorize.mockReturnValue(() => {});

    render(
      <MemoryRouter initialEntries={["/some-page"]}>
        <SecureRoute path="/some-page" element={<>You can only see this if you're logged in</>}></SecureRoute>
      </MemoryRouter>
    );

    expect(
      screen.getByText("You can only see this if you're logged in")
    ).toBeInTheDocument();
  });

But after upgrading to v6 it throws an error below

Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • TL;DR The `SecureRoute` cannot directly render a `Route` component, it should render the `Route` components in a `Routes` component. Or if it's really trying to serve as route protection, it should render an `Outlet` for nested routes it's protecting or the `Navigate` component to redirect to any login route. – Drew Reese Oct 04 '22 at 19:10

0 Answers0