import { describe, it, expect, beforeEach } from 'vitest' import { render, screen } from '@testing-library/react' import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom' import { ProtectedRoute } from '../ProtectedRoute' import { useAuthStore } from '@/store/authStore' /** * Probe component: surfaces the current pathname and `location.state.from` so * the test can assert both the redirect target and that the original * destination is preserved for post-login return. */ function LocationProbe() { const loc = useLocation() const from = (loc.state as { from?: { pathname?: string } } | null)?.from?.pathname ?? '' return ( <>
{loc.pathname}
{from}
) } describe('ProtectedRoute — unauthenticated redirect', () => { beforeEach(() => { useAuthStore.setState({ user: null, token: null, isAuthenticated: false, isLoading: false, }) }) it('redirects unauthenticated visits to /home → / and preserves origin in state.from', () => { render(
home
} /> } />
, ) // The protected page should not render. expect(screen.queryByTestId('home-content')).not.toBeInTheDocument() // We landed on / (the public landing route), not /landing. expect(screen.getByTestId('probe-pathname')).toHaveTextContent('/') expect(screen.getByTestId('probe-from')).toHaveTextContent('/home') }) })