All checks were successful
Deploy to Web Server flyer-crawler.projectium.com / deploy (push) Successful in 6m41s
213 lines
8.5 KiB
TypeScript
213 lines
8.5 KiB
TypeScript
// src/features/flyer/FlyerUploader.test.tsx
|
|
import React from 'react';
|
|
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
|
|
import { describe, it, expect, vi, beforeEach, afterEach, type Mocked, type Mock } from 'vitest';
|
|
import { FlyerUploader } from './FlyerUploader';
|
|
import * as aiApiClientModule from '../../services/aiApiClient';
|
|
import * as checksumModule from '../../utils/checksum';
|
|
import * as routerDomModule from 'react-router-dom';
|
|
|
|
// Mock dependencies
|
|
vi.mock('../../services/aiApiClient');
|
|
vi.mock('../../services/logger.client', () => ({
|
|
logger: {
|
|
info: vi.fn(),
|
|
error: vi.fn(),
|
|
},
|
|
}));
|
|
vi.mock('../../utils/checksum', () => ({
|
|
generateFileChecksum: vi.fn(),
|
|
}));
|
|
// Mock react-router-dom to spy on the navigate function
|
|
vi.mock('react-router-dom', async () => {
|
|
const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom');
|
|
return {
|
|
...actual,
|
|
useNavigate: vi.fn(),
|
|
};
|
|
});
|
|
|
|
// Get the mocked versions of the modules/functions
|
|
const mockedAiApiClient = aiApiClientModule as Mocked<typeof aiApiClientModule>;
|
|
const mockedChecksumModule = checksumModule as Mocked<typeof checksumModule>;
|
|
const mockedRouterDom = routerDomModule as Mocked<typeof routerDomModule>;
|
|
const navigateSpy = vi.fn();
|
|
|
|
const renderComponent = (onProcessingComplete = vi.fn()) => {
|
|
return render(
|
|
// We still use MemoryRouter to provide routing context for components like <Link>
|
|
<routerDomModule.MemoryRouter>
|
|
<FlyerUploader onProcessingComplete={onProcessingComplete} />
|
|
</routerDomModule.MemoryRouter>
|
|
);
|
|
};
|
|
|
|
describe('FlyerUploader', { timeout: 20000 }, () => {
|
|
beforeEach(() => {
|
|
// Use fake timers to control polling intervals (setTimeout) in tests.
|
|
vi.useFakeTimers();
|
|
vi.clearAllMocks();
|
|
// Access the mock implementation directly from the mocked module.
|
|
// This is the most robust way and avoids TypeScript confusion.
|
|
mockedChecksumModule.generateFileChecksum.mockResolvedValue('mock-checksum');
|
|
// Correctly type the mock for `useNavigate`.
|
|
// Since we've mocked `react-router-dom`, `useNavigate` is a `vi.fn()`. We just need to
|
|
// cast it to the imported `Mock` type so TypeScript knows it has methods like `mockReturnValue`.
|
|
(mockedRouterDom.useNavigate as Mock).mockReturnValue(navigateSpy);
|
|
});
|
|
|
|
afterEach(() => {
|
|
// Restore real timers after each test to avoid side effects.
|
|
vi.useRealTimers();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it('should render the initial state correctly', () => {
|
|
renderComponent();
|
|
expect(screen.getByText('Upload New Flyer')).toBeInTheDocument();
|
|
expect(screen.getByText('Click to select a file')).toBeInTheDocument();
|
|
expect(screen.getByText('Select a flyer (PDF or image) to begin.')).toBeInTheDocument();
|
|
});
|
|
|
|
it('should handle file upload and start polling', async () => {
|
|
mockedAiApiClient.uploadAndProcessFlyer.mockResolvedValue(
|
|
new Response(JSON.stringify({ jobId: 'job-123' }), { status: 200 })
|
|
);
|
|
// Mock the job status to return 'completed' on the first poll.
|
|
// This prevents the test from timing out due to an infinite polling loop.
|
|
mockedAiApiClient.getJobStatus.mockResolvedValue(new Response(JSON.stringify({ state: 'completed', returnValue: { flyerId: 42 } })));
|
|
|
|
renderComponent();
|
|
const file = new File(['content'], 'flyer.pdf', { type: 'application/pdf' });
|
|
const input = screen.getByLabelText(/click to select a file/i);
|
|
|
|
await act(async () => {
|
|
fireEvent.change(input, { target: { files: [file] } });
|
|
});
|
|
|
|
await waitFor(() => {
|
|
expect(mockedChecksumModule.generateFileChecksum).toHaveBeenCalledWith(file);
|
|
expect(mockedAiApiClient.uploadAndProcessFlyer).toHaveBeenCalledWith(file, 'mock-checksum');
|
|
// Check for the loading spinner as a more reliable indicator of the processing state.
|
|
expect(screen.getByTestId('loading-spinner')).toBeInTheDocument();
|
|
});
|
|
|
|
// Advance timers to allow the first poll to execute
|
|
await act(async () => {
|
|
await vi.runAllTimersAsync();
|
|
});
|
|
|
|
// Fast-forward time to trigger the poll and the subsequent redirect timeout.
|
|
await act(async () => { await vi.runAllTimersAsync(); });
|
|
|
|
});
|
|
|
|
it('should poll for status, complete successfully, and redirect', async () => {
|
|
const onProcessingComplete = vi.fn();
|
|
mockedAiApiClient.uploadAndProcessFlyer.mockResolvedValue(
|
|
new Response(JSON.stringify({ jobId: 'job-123' }), { status: 200 })
|
|
);
|
|
mockedAiApiClient.getJobStatus
|
|
.mockResolvedValueOnce(new Response(JSON.stringify({ state: 'active', progress: { message: 'Analyzing...' } })))
|
|
.mockResolvedValueOnce(new Response(JSON.stringify({ state: 'completed', returnValue: { flyerId: 42 } })));
|
|
|
|
renderComponent(onProcessingComplete);
|
|
const file = new File(['content'], 'flyer.pdf', { type: 'application/pdf' });
|
|
const input = screen.getByLabelText(/click to select a file/i);
|
|
|
|
await act(async () => {
|
|
fireEvent.change(input, { target: { files: [file] } });
|
|
});
|
|
|
|
await waitFor(() => expect(mockedAiApiClient.getJobStatus).toHaveBeenCalledWith('job-123'));
|
|
expect(screen.getByText('Analyzing...')).toBeInTheDocument();
|
|
|
|
await act(async () => {
|
|
await vi.runAllTimersAsync(); // Advance past the polling interval
|
|
});
|
|
|
|
await waitFor(() => {
|
|
expect(screen.getByText('Processing complete! Redirecting to flyer 42...')).toBeInTheDocument();
|
|
expect(onProcessingComplete).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
// Now, test the redirection by advancing the timer past the 1500ms timeout
|
|
await act(async () => {
|
|
await vi.runAllTimersAsync();
|
|
});
|
|
expect(navigateSpy).toHaveBeenCalledWith('/flyers/42');
|
|
});
|
|
|
|
it('should handle a failed job', async () => {
|
|
mockedAiApiClient.uploadAndProcessFlyer.mockResolvedValue(
|
|
new Response(JSON.stringify({ jobId: 'job-123' }), { status: 200 })
|
|
);
|
|
mockedAiApiClient.getJobStatus.mockResolvedValue(
|
|
new Response(JSON.stringify({ state: 'failed', failedReason: 'AI model exploded' }))
|
|
);
|
|
|
|
renderComponent();
|
|
const file = new File(['content'], 'flyer.pdf', { type: 'application/pdf' });
|
|
const input = screen.getByLabelText(/click to select a file/i);
|
|
|
|
await act(async () => {
|
|
fireEvent.change(input, { target: { files: [file] } });
|
|
});
|
|
|
|
await waitFor(() => {
|
|
expect(screen.getByText('Processing failed: AI model exploded')).toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
it('should handle a duplicate flyer error (409)', async () => {
|
|
mockedAiApiClient.uploadAndProcessFlyer.mockResolvedValue(
|
|
new Response(JSON.stringify({ flyerId: 99, message: 'Duplicate' }), { status: 409 })
|
|
);
|
|
|
|
renderComponent();
|
|
const file = new File(['content'], 'flyer.pdf', { type: 'application/pdf' });
|
|
const input = screen.getByLabelText(/click to select a file/i);
|
|
|
|
await act(async () => {
|
|
fireEvent.change(input, { target: { files: [file] } });
|
|
});
|
|
|
|
await waitFor(() => {
|
|
expect(screen.getByText('This flyer has already been processed. You can view it here:')).toBeInTheDocument();
|
|
expect(screen.getByRole('link', { name: 'Flyer #99' })).toHaveAttribute('href', '/flyers/99');
|
|
});
|
|
});
|
|
|
|
it('should allow the user to stop watching progress', async () => {
|
|
mockedAiApiClient.uploadAndProcessFlyer.mockResolvedValue(
|
|
new Response(JSON.stringify({ jobId: 'job-123' }), { status: 200 })
|
|
);
|
|
// Mock getJobStatus to keep the component in a polling state
|
|
mockedAiApiClient.getJobStatus.mockResolvedValue(
|
|
new Response(JSON.stringify({ state: 'active', progress: { message: 'Analyzing...' } }))
|
|
);
|
|
|
|
renderComponent();
|
|
const file = new File(['content'], 'flyer.pdf', { type: 'application/pdf' });
|
|
const input = screen.getByLabelText(/click to select a file/i);
|
|
|
|
await act(async () => {
|
|
fireEvent.change(input, { target: { files: [file] } });
|
|
});
|
|
|
|
// Wait for the component to enter the polling state and for the button to appear
|
|
const stopButton = await screen.findByRole('button', { name: 'Stop Watching Progress' });
|
|
expect(stopButton).toBeInTheDocument();
|
|
expect(mockedAiApiClient.getJobStatus).toHaveBeenCalledTimes(1);
|
|
|
|
// Click the button to cancel polling
|
|
fireEvent.click(stopButton);
|
|
|
|
// Assert that the UI has returned to its initial idle state
|
|
await waitFor(() => {
|
|
expect(screen.getByText('Click to select a file')).toBeInTheDocument();
|
|
expect(screen.getByText('Select a flyer (PDF or image) to begin.')).toBeInTheDocument();
|
|
expect(screen.queryByRole('button', { name: 'Stop Watching Progress' })).not.toBeInTheDocument();
|
|
});
|
|
});
|
|
}); |