The previous fix only prioritized authStore inside the route guard, so an unauthenticated NextAuth session or a suppressed access-context 401 still collapsed into an empty permission set. Propagate both authentication signals before authorization so expired sessions consistently reauthenticate.
66 lines
2.0 KiB
TypeScript
66 lines
2.0 KiB
TypeScript
import { render, screen } from "@testing-library/react";
|
|
|
|
import { useAccessStore } from "@/store/accessStore";
|
|
import { useAuthStore } from "@/store/authStore";
|
|
import { RoutePermissionGuard } from "./RoutePermissionGuard";
|
|
|
|
jest.mock("next/navigation", () => ({
|
|
usePathname: () => "/network-simulation",
|
|
}));
|
|
|
|
describe("RoutePermissionGuard", () => {
|
|
beforeEach(() => {
|
|
useAccessStore.setState({
|
|
context: null,
|
|
permissions: [],
|
|
loading: false,
|
|
});
|
|
useAuthStore.setState({
|
|
accessToken: null,
|
|
sessionExpired: false,
|
|
sessionExpiryReason: null,
|
|
});
|
|
});
|
|
|
|
it("prioritizes an expired session over a missing route permission", () => {
|
|
useAuthStore.setState({
|
|
sessionExpired: true,
|
|
sessionExpiryReason: "unauthorized",
|
|
});
|
|
|
|
render(
|
|
<RoutePermissionGuard authenticated>
|
|
<div>受保护内容</div>
|
|
</RoutePermissionGuard>,
|
|
);
|
|
|
|
expect(screen.getByText("登录状态已失效")).toBeInTheDocument();
|
|
expect(screen.getByText("正在跳转到登录页面…")).toBeInTheDocument();
|
|
expect(screen.queryByText("无权访问此功能")).not.toBeInTheDocument();
|
|
expect(screen.queryByText(/simulation\.view/)).not.toBeInTheDocument();
|
|
expect(screen.queryByText("受保护内容")).not.toBeInTheDocument();
|
|
});
|
|
|
|
it("shows the permission error when the session is still valid", () => {
|
|
render(
|
|
<RoutePermissionGuard authenticated>
|
|
<div>受保护内容</div>
|
|
</RoutePermissionGuard>,
|
|
);
|
|
|
|
expect(screen.getByText("无权访问此功能")).toBeInTheDocument();
|
|
expect(screen.getByText(/simulation\.view/)).toBeInTheDocument();
|
|
});
|
|
|
|
it("checks authentication before the expired state effect runs", () => {
|
|
render(
|
|
<RoutePermissionGuard authenticated={false}>
|
|
<div>受保护内容</div>
|
|
</RoutePermissionGuard>,
|
|
);
|
|
|
|
expect(screen.getByText("登录状态已失效")).toBeInTheDocument();
|
|
expect(screen.queryByText("无权访问此功能")).not.toBeInTheDocument();
|
|
});
|
|
});
|