When i try to check if the navigate method is called with '/' Getting following error

Error: [vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock```

Here are the files:-

//useAuthentication.ts
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { getCookie } from '../utility/cookieUtils';
import authService from '../services/authService';

type UseAuthenticationType = {
  isAuthenticated: boolean;
  login: (username: string, password: string) => Promise<void>;
  userName: string | null;
  isLoginError: boolean;
};
const useAuthentication = (): UseAuthenticationType => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [userName, setUserName] = useState<string | null>(null);
  const [isLoginError, setIsLoginError] = useState<boolean>(false);
  const navigate = useNavigate();

  useEffect(() => {
    const cookie = getCookie('jwtToken');

    const user = localStorage.getItem('username');
    if (user !== null) {
      setUserName(user);
    }
    if (cookie.length) {
      setIsAuthenticated(true);
    } else {
      navigate('/');
      localStorage.removeItem('username');
    }
  }, [navigate]);

  const handleLogin = async (username: string, password: string) => {
    try {
      const data = await authService.login(username, password);
      setIsAuthenticated(true);
      setUserName(data.username);
      navigate('/order-entry');
      localStorage.setItem('username', data.username);
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error('Error signing in:', error);
      setIsLoginError(true);
      setIsAuthenticated(false);
    }
  };

  return { isAuthenticated, login: handleLogin, userName, isLoginError };
};

export default useAuthentication;

//useAuthentication.test.ts
import { describe, expect, it, vi } from 'vitest';
import { renderHook } from '@testing-library/react';
import useAuthentication from './useAuthentication';

// Mock the cookieUtils module
vi.mock('../utility/cookieUtils', () => ({
  getCookie: vi.fn().mockReturnValue(''), // Mocking getCookie to return empty string
}));

describe('useAuthentication hook', () => {
  it('should call navigate with "/" when cookie is not present', () => {
    // Mock the navigate function
    const mockNavigate = vi.fn();

    // Mock useNavigate hook
    vi.mock('react-router-dom', async () => {
      const mod = await vi.importActual('react-router-dom');
      return {
        ...mod,
        useNavigate: vi.fn().mockReturnValue(mockNavigate),
      };
    });

    // Render the hook
    renderHook(() => useAuthentication());

    // Check that navigate was called with "/"
    expect(mockNavigate).toHaveBeenCalledWith('/');
  });
});

0

There are 0 best solutions below