Files
flyer-crawler.projectium.com/src/components/FlyerCountDisplay.test.tsx
Torben Sorensen 19885a50f7
All checks were successful
Deploy to Test Environment / deploy-to-test (push) Successful in 13m30s
unit test auto-provider refactor
2026-01-01 23:12:32 -08:00

85 lines
2.8 KiB
TypeScript

// src/components/FlyerCountDisplay.test.tsx
import React from 'react';
import { screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { FlyerCountDisplay } from './FlyerCountDisplay';
import { useFlyers } from '../hooks/useFlyers';
import type { Flyer } from '../types';
import { createMockFlyer } from '../tests/utils/mockFactories';
import { renderWithProviders } from '../tests/utils/renderWithProviders';
// Mock the dependencies
vi.mock('../hooks/useFlyers');
// Create typed mocks
const mockedUseFlyers = vi.mocked(useFlyers);
describe('FlyerCountDisplay', () => {
beforeEach(() => {
// Reset mocks before each test to ensure they are isolated.
vi.clearAllMocks();
});
it('should render a loading state when isLoading is true', () => {
// Arrange: For this specific test, override the mock to return a loading state.
mockedUseFlyers.mockReturnValue({
flyers: [],
isLoadingFlyers: true,
flyersError: null,
fetchNextFlyersPage: vi.fn(),
hasNextFlyersPage: false,
isRefetchingFlyers: false,
refetchFlyers: vi.fn(),
});
// Act: Render the component.
renderWithProviders(<FlyerCountDisplay />);
// Assert: Check that the loading spinner is visible.
expect(screen.getByTestId('loading-spinner')).toBeInTheDocument();
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
it('should render an error message when an error is present', () => {
// Arrange: Override the mock to return an error state.
const errorMessage = 'Failed to fetch data';
mockedUseFlyers.mockReturnValue({
flyers: [],
isLoadingFlyers: false,
flyersError: new Error(errorMessage),
fetchNextFlyersPage: vi.fn(),
hasNextFlyersPage: false,
isRefetchingFlyers: false,
refetchFlyers: vi.fn(),
});
// Act
renderWithProviders(<FlyerCountDisplay />);
// Assert: Check that the error message is displayed.
expect(screen.getByRole('alert')).toHaveTextContent(errorMessage);
});
it('should render the flyer count when data is successfully loaded', () => {
// Arrange: Override the mock to return a successful state with some data.
const mockFlyers: Flyer[] = [createMockFlyer(), createMockFlyer()];
mockedUseFlyers.mockReturnValue({
flyers: mockFlyers,
isLoadingFlyers: false,
flyersError: null,
fetchNextFlyersPage: vi.fn(),
hasNextFlyersPage: false,
isRefetchingFlyers: false,
refetchFlyers: vi.fn(),
});
// Act
renderWithProviders(<FlyerCountDisplay />);
// Assert: Check that the correct count is displayed.
const countDisplay = screen.getByTestId('flyer-count');
expect(countDisplay).toBeInTheDocument();
expect(countDisplay).toHaveTextContent('Number of flyers: 2');
});
});