2026-01-07 09:31:02 +00:00
|
|
|
import { render, screen, waitFor } from '@testing-library/react';
|
|
|
|
|
import { describe, it, expect, vi } from 'vitest';
|
|
|
|
|
import { createLazyComponent } from './LazyComponent';
|
|
|
|
|
import { Suspense } from 'react';
|
|
|
|
|
|
|
|
|
|
// Mock component
|
|
|
|
|
const MockComponent = () => <div>Lazy Loaded Component</div>;
|
|
|
|
|
|
|
|
|
|
describe('LazyComponent', () => {
|
|
|
|
|
it('creates lazy component factory', () => {
|
2026-01-13 18:47:57 +00:00
|
|
|
const LazyTest = createLazyComponent(() =>
|
|
|
|
|
Promise.resolve({ default: MockComponent }),
|
2026-01-07 09:31:02 +00:00
|
|
|
);
|
2026-01-13 18:47:57 +00:00
|
|
|
|
2026-01-07 09:31:02 +00:00
|
|
|
expect(LazyTest).toBeDefined();
|
|
|
|
|
expect(typeof LazyTest).toBe('function');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('renders lazy component when loaded', async () => {
|
2026-01-13 18:47:57 +00:00
|
|
|
const LazyTest = createLazyComponent(() =>
|
|
|
|
|
Promise.resolve({ default: MockComponent }),
|
2026-01-07 09:31:02 +00:00
|
|
|
);
|
2026-01-13 18:47:57 +00:00
|
|
|
|
2026-01-07 09:31:02 +00:00
|
|
|
render(
|
|
|
|
|
<Suspense fallback={<div>Loading...</div>}>
|
|
|
|
|
<LazyTest />
|
2026-01-13 18:47:57 +00:00
|
|
|
</Suspense>,
|
2026-01-07 09:31:02 +00:00
|
|
|
);
|
2026-01-13 18:47:57 +00:00
|
|
|
|
2026-01-07 09:31:02 +00:00
|
|
|
await waitFor(() => {
|
|
|
|
|
expect(screen.getByText('Lazy Loaded Component')).toBeInTheDocument();
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('shows fallback while loading', () => {
|
|
|
|
|
const LazyTest = createLazyComponent(
|
2026-01-13 18:47:57 +00:00
|
|
|
() => new Promise(() => {}), // Never resolves
|
2026-01-07 09:31:02 +00:00
|
|
|
);
|
2026-01-13 18:47:57 +00:00
|
|
|
|
2026-01-07 09:31:02 +00:00
|
|
|
render(
|
|
|
|
|
<Suspense fallback={<div>Loading...</div>}>
|
|
|
|
|
<LazyTest />
|
2026-01-13 18:47:57 +00:00
|
|
|
</Suspense>,
|
2026-01-07 09:31:02 +00:00
|
|
|
);
|
2026-01-13 18:47:57 +00:00
|
|
|
|
2026-01-07 09:31:02 +00:00
|
|
|
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('uses custom fallback when provided', () => {
|
|
|
|
|
const LazyTest = createLazyComponent(
|
|
|
|
|
() => new Promise(() => {}),
|
2026-01-13 18:47:57 +00:00
|
|
|
<div>Custom Loading...</div>,
|
2026-01-07 09:31:02 +00:00
|
|
|
);
|
2026-01-13 18:47:57 +00:00
|
|
|
|
2026-01-07 09:31:02 +00:00
|
|
|
render(
|
|
|
|
|
<Suspense fallback={<div>Default Loading...</div>}>
|
|
|
|
|
<LazyTest fallback={<div>Custom Loading...</div>} />
|
2026-01-13 18:47:57 +00:00
|
|
|
</Suspense>,
|
2026-01-07 09:31:02 +00:00
|
|
|
);
|
2026-01-13 18:47:57 +00:00
|
|
|
|
2026-01-07 09:31:02 +00:00
|
|
|
// The Suspense fallback will show, but the component can also have its own
|
|
|
|
|
expect(screen.getByText('Default Loading...')).toBeInTheDocument();
|
|
|
|
|
});
|
|
|
|
|
});
|