1- import { render , screen } from '@testing-library/react' ;
1+ import { render , screen , waitFor } from '@testing-library/react' ;
22import { LandingPage } from '../LandingPage' ;
33
4+ const mockedNavigate = jest . fn ( ) ;
5+ const consoleErrorSpy = jest
6+ . spyOn ( console , 'error' )
7+ . mockImplementation ( ( ) => { } ) ;
8+
49// Mock dependencies
510jest . mock ( '../LandingComponents/Navbar/Navbar' , ( ) => ( {
611 Navbar : ( ) => < div > Mocked Navbar</ div > ,
@@ -27,7 +32,28 @@ jest.mock('../../components/utils/ScrollToTop', () => ({
2732 ScrollToTop : ( ) => < div > Mocked ScrollToTop</ div > ,
2833} ) ) ;
2934
35+ jest . mock ( 'react-router' , ( ) => ( {
36+ useNavigate : ( ) => mockedNavigate ,
37+ } ) ) ;
38+
39+ jest . mock ( '@/components/utils/URLs' , ( ) => ( {
40+ url : {
41+ backendURL : 'http://mocked-backend-url/' ,
42+ } ,
43+ } ) ) ;
44+
45+ global . fetch = jest . fn ( ( ) =>
46+ Promise . resolve ( {
47+ ok : false ,
48+ } )
49+ ) as jest . Mock ;
50+
3051describe ( 'LandingPage' , ( ) => {
52+ afterEach ( ( ) => {
53+ jest . clearAllMocks ( ) ;
54+ consoleErrorSpy . mockClear ( ) ;
55+ } ) ;
56+
3157 it ( 'renders all components correctly' , ( ) => {
3258 render ( < LandingPage /> ) ;
3359
@@ -40,6 +66,45 @@ describe('LandingPage', () => {
4066 expect ( screen . getByText ( 'Mocked Footer' ) ) . toBeInTheDocument ( ) ;
4167 expect ( screen . getByText ( 'Mocked ScrollToTop' ) ) . toBeInTheDocument ( ) ;
4268 } ) ;
69+
70+ it ( 'redirects to /home when the user is already logged in' , async ( ) => {
71+ ( fetch as jest . Mock ) . mockResolvedValueOnce ( {
72+ ok : true ,
73+ } ) ;
74+
75+ render ( < LandingPage /> ) ;
76+
77+ await waitFor ( ( ) => {
78+ expect ( mockedNavigate ) . toHaveBeenCalledWith ( '/home' ) ;
79+ } ) ;
80+ expect ( fetch ) . toHaveBeenCalledWith ( 'http://mocked-backend-url/api/user' , {
81+ method : 'GET' ,
82+ credentials : 'include' ,
83+ } ) ;
84+ } ) ;
85+
86+ it ( 'stays on the landing page when the user is not logged in' , async ( ) => {
87+ render ( < LandingPage /> ) ;
88+
89+ await waitFor ( ( ) => {
90+ expect ( fetch ) . toHaveBeenCalledWith ( 'http://mocked-backend-url/api/user' , {
91+ method : 'GET' ,
92+ credentials : 'include' ,
93+ } ) ;
94+ } ) ;
95+ expect ( mockedNavigate ) . not . toHaveBeenCalled ( ) ;
96+ } ) ;
97+
98+ it ( 'stays on the landing page when the session check fails' , async ( ) => {
99+ ( fetch as jest . Mock ) . mockRejectedValueOnce ( new Error ( 'network error' ) ) ;
100+
101+ render ( < LandingPage /> ) ;
102+
103+ await waitFor ( ( ) => {
104+ expect ( consoleErrorSpy ) . toHaveBeenCalled ( ) ;
105+ } ) ;
106+ expect ( mockedNavigate ) . not . toHaveBeenCalled ( ) ;
107+ } ) ;
43108} ) ;
44109
45110describe ( 'LandingPage Component using Snapshot' , ( ) => {
0 commit comments