import { renderHook } from '@testing-library/react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { usePreload, usePreloadRoute } from './usePreload'; describe('usePreload', () => { beforeEach(() => { vi.clearAllMocks(); // Clean up any existing preload links document .querySelectorAll('link[rel="preload"], link[rel="prefetch"]') .forEach((link) => link.remove()); }); afterEach(() => { // Clean up after each test document .querySelectorAll('link[rel="preload"], link[rel="prefetch"]') .forEach((link) => link.remove()); }); it('should preload images', () => { renderHook(() => usePreload({ images: ['https://example.com/image.jpg'], }), ); const link = document.querySelector('link[rel="preload"][as="image"]'); expect(link).toBeInTheDocument(); expect(link).toHaveAttribute('href', 'https://example.com/image.jpg'); }); it('should preload scripts', () => { renderHook(() => usePreload({ scripts: ['https://example.com/script.js'], }), ); const link = document.querySelector('link[rel="preload"][as="script"]'); expect(link).toBeInTheDocument(); expect(link).toHaveAttribute('href', 'https://example.com/script.js'); }); it('should preload styles', () => { renderHook(() => usePreload({ styles: ['https://example.com/style.css'], }), ); const link = document.querySelector('link[rel="preload"][as="style"]'); expect(link).toBeInTheDocument(); expect(link).toHaveAttribute('href', 'https://example.com/style.css'); }); it('should prefetch resources', () => { renderHook(() => usePreload({ prefetch: ['https://example.com/resource'], }), ); const link = document.querySelector('link[rel="prefetch"]'); expect(link).toBeInTheDocument(); expect(link).toHaveAttribute('href', 'https://example.com/resource'); }); it('should cleanup preload links on unmount', () => { const { unmount } = renderHook(() => usePreload({ images: ['https://example.com/image.jpg'], }), ); expect(document.querySelector('link[rel="preload"]')).toBeInTheDocument(); unmount(); // Links should be cleaned up expect( document.querySelector('link[rel="preload"]'), ).not.toBeInTheDocument(); }); }); describe('usePreloadRoute', () => { beforeEach(() => { vi.clearAllMocks(); document .querySelectorAll('link[rel="prefetch"]') .forEach((link) => link.remove()); }); afterEach(() => { document .querySelectorAll('link[rel="prefetch"]') .forEach((link) => link.remove()); }); it('should prefetch route', () => { renderHook(() => usePreloadRoute('/test-route')); const link = document.querySelector('link[rel="prefetch"]'); expect(link).toBeInTheDocument(); expect(link).toHaveAttribute('href', '/test-route'); }); it('should cleanup prefetch link on unmount', () => { const { unmount } = renderHook(() => usePreloadRoute('/test-route')); expect(document.querySelector('link[rel="prefetch"]')).toBeInTheDocument(); unmount(); expect( document.querySelector('link[rel="prefetch"]'), ).not.toBeInTheDocument(); }); });