Here are frontend test scripts to validate all tasks using React Testing Library and Jest. These tests will ensure functionality, edge cases, and UI behavior are properly validated.
1. MarketItemCard Component Tests
File: components/MarketItemCard.test.jsx
import { render, fireEvent } from '@testing-library/react';
import MarketItemCard from './MarketItemCard';
import { supabase } from '../utils/supabaseClient'; // Mock this
// Mock Supabase and dynamic imports
jest.mock('../utils/supabase/projects', () => ({
linkToProject: jest.fn(),
}));
jest.mock('next/dynamic', () => () => ({ /* Mock dynamic component */ }));
describe('MarketItemCard', () => {
it('renders the project link button', () => {
const { getByTestId } = render(
<MarketItemCard market_item_id={123} />
);
expect(getByTestId('project-link-button')).toBeInTheDocument();
});
it('invokes linkToProject on button click', async () => {
const mockLinkToProject = jest.fn();
jest.mock('../utils/supabase/projects', () => ({
linkToProject: mockLinkToProject,
}));
const { getByTestId } = render(
<MarketItemCard market_item_id={123} />
);
fireEvent.click(getByTestId('project-link-button'));
expect(mockLinkToProject).toHaveBeenCalledWith(123);
});
it('handles unauthenticated users', () => {
// Mock auth state
supabase.auth.user = () => null;
const { getByTestId } = render(
<MarketItemCard market_item_id={123} />
);
fireEvent.click(getByTestId('project-link-button'));
expect(window.alert).toHaveBeenCalledWith('User not authenticated');
});
});
2. generateProjectName Utility Tests
File: utils/supabase/projects.test.jsx
import { generateProjectName } from './projects';
import { supabase } from '../supabaseClient';
describe('generateProjectName', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('returns a valid project name with first name', async () => {
const mockData = { first_name: 'Alice' };
supabase.from = jest.fn().mockReturnValue({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
single: jest.fn().mockResolvedValue({ data: mockData }),
});
const result = await generateProjectName('user123');
expect(result).toBe("Alice's First Project");
});
it('handles missing first name', async () => {
const mockData = { first_name: null };
supabase.from = jest.fn().mockReturnValue({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
single: jest.fn().mockResolvedValue({ data: mockData }),
});
const result = await generateProjectName('user123');
expect(result).toBe("User's First Project");
});
it('throws an error on fetch failure', async () => {
supabase.from = jest.fn().mockReturnValue({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
single: jest.fn().mockRejectedValue(new Error('API error')),
});
await expect(generateProjectName('user123')).rejects.toThrow(
'Failed to fetch user profile'
);
});
});
3. linkToProject Logic Tests
File: utils/supabase/projects.test.jsx (continued)
describe('linkToProject', () => {
it('creates a new project', async () => {
supabase.from = jest.fn().mockReturnValue({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
single: jest.fn().mockResolvedValue({ data: null }), // No existing project
});
supabase.from('projects').upsert = jest.fn().mockResolvedValue({
data: { id: 'proj123' },
});
await linkToProject('user123', 456);
expect(supabase.from('projects').upsert).toHaveBeenCalledWith(
expect.objectContaining({
user_id: 'user123',
market_item_id: 456,
})
);
});
it('updates an existing project', async () => {
supabase.from = jest.fn().mockReturnValue({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
single: jest.fn().mockResolvedValue({ data: { id: 'proj123' } }), // Existing project
});
supabase.from('projects').upsert = jest.fn().mockResolvedValue({
data: { id: 'proj123' },
});
await linkToProject('user123', 789);
expect(supabase.from('projects').upsert).toHaveBeenCalledWith(
expect.objectContaining({
id: 'proj123', // Updates existing project
market_item_id: 789,
})
);
});
it('handles upsert errors', async () => {
supabase.from('projects').upsert = jest.fn().mockRejectedValue(new Error('DB error'));
await expect(linkToProject('user123', 101)).rejects.toThrow('Upsert failed');
});
});
4. Project Management Page Tests
File: pages/projects/[id].test.jsx
import { render, screen } from '@testing-library/react';
import ProjectPage from './[id]';
import { supabase } from '../../utils/supabaseClient';
describe('ProjectPage', () => {
it('displays project details when linked', async () => {
const mockProject = {
id: 'proj123',
project_name: 'Alice\'s Project',
market_items: { title: 'Item X', description: 'Sample item' },
};
jest.mock('../../utils/supabase/projects', () => ({
getServerSideProps: jest.fn().mockResolvedValue({ props: { project: mockProject } }),
}));
const { container } = render(<ProjectPage project={mockProject} />);
expect(screen.getByText('Alice\'s Project')).toBeInTheDocument();
expect(screen.getByText('Item X')).toBeInTheDocument();
});
it('handles unlinked projects', async () => {
const mockProject = { project_name: 'Bob\'s Project', market_items: null };
const { container } = render(<ProjectPage project={mockProject} />);
expect(screen.getByText('No market item linked.')).toBeInTheDocument();
});
it('removes a linked project', async () => {
const mockProject = { id: 'proj123', market_items: { id: 456 } };
jest.spyOn(supabase.from('projects'), 'update').mockResolvedValue({ data: {} });
const { container } = render(<ProjectPage project={mockProject} />);
fireEvent.click(screen.getByText('Remove'));
expect(supabase.from('projects').update).toHaveBeenCalledWith(
{ market_item_id: null },
expect.anything()
);
});
it('shows 404 for invalid project IDs', async () => {
supabase.from = jest.fn().mockReturnValue({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
single: jest.fn().mockRejectedValue(new Error('Not found')),
});
const getServerSideProps = await ProjectPage.getInitialProps({ params: { id: 'invalid' } });
expect(getServerSideProps).toEqual({ notFound: true });
});
});
5. Cross-Component Tests (Integration)
File: integration/project-flow.test.jsx
import { render, fireEvent } from '@testing-library/react';
import MarketItemCard from '../components/MarketItemCard';
import ProjectPage from '../pages/projects/[id]';
import { supabase } from '../utils/supabaseClient';
describe('Project Flow', () => {
it('links a project and displays it', async () => {
// Mock Supabase functions
const mockLinkToProject = jest.fn().mockResolvedValue({ id: 'proj123' });
jest.mock('../utils/supabase/projects', () => ({
linkToProject: mockLinkToProject,
}));
// Test MarketItemCard linking
const { container } = render(<MarketItemCard market_item_id={123} />);
fireEvent.click(screen.getByTestId('project-link-button'));
expect(mockLinkToProject).toHaveBeenCalledWith(123);
// Test ProjectPage display
const mockProject = { id: 'proj123', market_items: { title: 'Test Item' } };
jest.mock('../pages/projects/[id]', () => ({
ProjectPage: () => <div data-testid="project-title">{mockProject.title}</div>,
}));
render(<ProjectPage project={mockProject} />);
expect(screen.getByTestId('project-title')).toHaveTextContent('Test Item');
});
});
Setup Instructions for Testing
-
Install Dependencies:
npm install @testing-library/react @testing-library/jest-dom jest supertest
-
Configure Jest:
- Add
setupFilesAfterEnv: Mock Supabase and dynamic imports in setupTests.js:
// jest.setup.js
jest.mock('next/dynamic', () => () => ({
// Mock dynamic components here
}));
jest.mock('../utils/supabaseClient', () => ({
supabase: {
from: jest.fn(),
auth: { user: () => ({ id: 'test-user' }) },
},
}));
-
Run Tests:
npm test
Key Test Coverage Areas
-
UI Interactions:
- Button clicks, modal triggers, and form submissions.
-
Edge Cases:
- Missing user data, unauthenticated users, and API errors.
-
Data Flow:
- Ensure Supabase mock functions are called with correct parameters.
-
Error Handling:
- Verify error alerts and fallback states (e.g., "User's First Project").
-
Performance:
- Verify dynamic imports are properly mocked to avoid runtime errors.
Final Notes:
- Run tests incrementally after each task to catch regressions early.
- Use Cypress for end-to-end testing if needed.
- Add Visual Regression Testing with Storybook for UI consistency.
Let me know if you need help setting up the testing environment! 🧪