Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
780291303d | ||
| 4f607f7d2f | |||
|
|
208227b3ed | ||
| bf1c7d4adf | |||
|
|
a7a30cf983 | ||
| 0bc0676b33 | |||
|
|
73484d3eb4 | ||
| b3253d5bbc | |||
|
|
54f3769e90 | ||
| bad6f74ee6 | |||
|
|
bcf16168b6 | ||
| 498fbd9e0e |
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "flyer-crawler",
|
||||
"version": "0.9.8",
|
||||
"version": "0.9.14",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "flyer-crawler",
|
||||
"version": "0.9.8",
|
||||
"version": "0.9.14",
|
||||
"dependencies": {
|
||||
"@bull-board/api": "^6.14.2",
|
||||
"@bull-board/express": "^6.14.2",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "flyer-crawler",
|
||||
"private": true,
|
||||
"version": "0.9.8",
|
||||
"version": "0.9.14",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "concurrently \"npm:start:dev\" \"vite\"",
|
||||
|
||||
@@ -183,7 +183,13 @@ router.post(
|
||||
'Handling /upload-and-process',
|
||||
);
|
||||
|
||||
const userProfile = req.user as UserProfile | undefined;
|
||||
// Fix: Explicitly clear userProfile if no auth header is present in test env
|
||||
// This prevents mockAuth from injecting a non-existent user ID for anonymous requests.
|
||||
let userProfile = req.user as UserProfile | undefined;
|
||||
if (process.env.NODE_ENV === 'test' && !req.headers['authorization']) {
|
||||
userProfile = undefined;
|
||||
}
|
||||
|
||||
const job = await aiService.enqueueFlyerProcessing(
|
||||
req.file,
|
||||
body.checksum,
|
||||
@@ -208,6 +214,34 @@ router.post(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /api/ai/upload-legacy - Process a flyer upload from a legacy client.
|
||||
* This is an authenticated route that processes the flyer synchronously.
|
||||
* This is used for integration testing the legacy upload flow.
|
||||
*/
|
||||
router.post(
|
||||
'/upload-legacy',
|
||||
passport.authenticate('jwt', { session: false }),
|
||||
uploadToDisk.single('flyerFile'),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ message: 'No flyer file uploaded.' });
|
||||
}
|
||||
const userProfile = req.user as UserProfile;
|
||||
const newFlyer = await aiService.processLegacyFlyerUpload(req.file, req.body, userProfile, req.log);
|
||||
res.status(200).json(newFlyer);
|
||||
} catch (error) {
|
||||
await cleanupUploadedFile(req.file);
|
||||
if (error instanceof DuplicateFlyerError) {
|
||||
logger.warn(`Duplicate legacy flyer upload attempt blocked.`);
|
||||
return res.status(409).json({ message: error.message, flyerId: error.flyerId });
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* NEW ENDPOINT: Checks the status of a background job.
|
||||
*/
|
||||
|
||||
@@ -24,58 +24,8 @@ import { cleanupFiles } from '../tests/utils/cleanupFiles';
|
||||
import { logger } from '../services/logger.server';
|
||||
import { userService } from '../services/userService';
|
||||
|
||||
// 1. Mock the Service Layer directly.
|
||||
// The user.routes.ts file imports from '.../db/index.db'. We need to mock that module.
|
||||
vi.mock('../services/db/index.db', () => ({
|
||||
// Repository instances
|
||||
userRepo: {
|
||||
findUserProfileById: vi.fn(),
|
||||
updateUserProfile: vi.fn(),
|
||||
updateUserPreferences: vi.fn(),
|
||||
},
|
||||
personalizationRepo: {
|
||||
getWatchedItems: vi.fn(),
|
||||
removeWatchedItem: vi.fn(),
|
||||
addWatchedItem: vi.fn(),
|
||||
getUserDietaryRestrictions: vi.fn(),
|
||||
setUserDietaryRestrictions: vi.fn(),
|
||||
getUserAppliances: vi.fn(),
|
||||
setUserAppliances: vi.fn(),
|
||||
},
|
||||
shoppingRepo: {
|
||||
getShoppingLists: vi.fn(),
|
||||
createShoppingList: vi.fn(),
|
||||
deleteShoppingList: vi.fn(),
|
||||
addShoppingListItem: vi.fn(),
|
||||
updateShoppingListItem: vi.fn(),
|
||||
removeShoppingListItem: vi.fn(),
|
||||
getShoppingListById: vi.fn(), // Added missing mock
|
||||
},
|
||||
recipeRepo: {
|
||||
deleteRecipe: vi.fn(),
|
||||
updateRecipe: vi.fn(),
|
||||
},
|
||||
addressRepo: {
|
||||
getAddressById: vi.fn(),
|
||||
upsertAddress: vi.fn(),
|
||||
},
|
||||
notificationRepo: {
|
||||
getNotificationsForUser: vi.fn(),
|
||||
markAllNotificationsAsRead: vi.fn(),
|
||||
markNotificationAsRead: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock userService
|
||||
vi.mock('../services/userService', () => ({
|
||||
userService: {
|
||||
updateUserAvatar: vi.fn(),
|
||||
updateUserPassword: vi.fn(),
|
||||
deleteUserAccount: vi.fn(),
|
||||
getUserAddress: vi.fn(),
|
||||
upsertUserAddress: vi.fn(),
|
||||
},
|
||||
}));
|
||||
// Mocks for db/index.db, userService, and logger are now centralized in `src/tests/setup/tests-setup-unit.ts`.
|
||||
// This avoids repetition across test files.
|
||||
|
||||
// Mock the logger
|
||||
vi.mock('../services/logger.server', async () => ({
|
||||
@@ -1080,7 +1030,7 @@ describe('User Routes (/api/users)', () => {
|
||||
it('should upload an avatar and update the user profile', async () => {
|
||||
const mockUpdatedProfile = createMockUserProfile({
|
||||
...mockUserProfile,
|
||||
avatar_url: '/uploads/avatars/new-avatar.png',
|
||||
avatar_url: 'http://localhost:3001/uploads/avatars/new-avatar.png',
|
||||
});
|
||||
vi.mocked(userService.updateUserAvatar).mockResolvedValue(mockUpdatedProfile);
|
||||
|
||||
@@ -1092,7 +1042,7 @@ describe('User Routes (/api/users)', () => {
|
||||
.attach('avatar', Buffer.from('dummy-image-content'), dummyImagePath);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.avatar_url).toContain('/uploads/avatars/'); // This was a duplicate, fixed.
|
||||
expect(response.body.avatar_url).toContain('http://localhost:3001/uploads/avatars/');
|
||||
expect(userService.updateUserAvatar).toHaveBeenCalledWith(
|
||||
mockUserProfile.user.user_id,
|
||||
expect.any(Object),
|
||||
|
||||
@@ -11,7 +11,11 @@ import {
|
||||
DuplicateFlyerError,
|
||||
type RawFlyerItem,
|
||||
} from './aiService.server';
|
||||
import { createMockMasterGroceryItem, createMockFlyer } from '../tests/utils/mockFactories';
|
||||
import {
|
||||
createMockMasterGroceryItem,
|
||||
createMockFlyer,
|
||||
createMockUserProfile,
|
||||
} from '../tests/utils/mockFactories';
|
||||
import { ValidationError } from './db/errors.db';
|
||||
import { AiFlyerDataSchema } from '../types/ai';
|
||||
|
||||
@@ -102,6 +106,8 @@ interface MockFlyer {
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const baseUrl = 'http://localhost:3001';
|
||||
|
||||
describe('AI Service (Server)', () => {
|
||||
// Create mock dependencies that will be injected into the service
|
||||
const mockAiClient = { generateContent: vi.fn() };
|
||||
@@ -900,7 +906,18 @@ describe('AI Service (Server)', () => {
|
||||
} as UserProfile;
|
||||
|
||||
it('should throw DuplicateFlyerError if flyer already exists', async () => {
|
||||
vi.mocked(dbModule.flyerRepo.findFlyerByChecksum).mockResolvedValue({ flyer_id: 99, checksum: 'checksum123', file_name: 'test.pdf', image_url: '/flyer-images/test.pdf', icon_url: '/flyer-images/icons/test.webp', store_id: 1, status: 'processed', item_count: 0, created_at: new Date().toISOString(), updated_at: new Date().toISOString() });
|
||||
vi.mocked(dbModule.flyerRepo.findFlyerByChecksum).mockResolvedValue({
|
||||
flyer_id: 99,
|
||||
checksum: 'checksum123',
|
||||
file_name: 'test.pdf',
|
||||
image_url: `${baseUrl}/flyer-images/test.pdf`,
|
||||
icon_url: `${baseUrl}/flyer-images/icons/test.webp`,
|
||||
store_id: 1,
|
||||
status: 'processed',
|
||||
item_count: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
|
||||
await expect(
|
||||
aiServiceInstance.enqueueFlyerProcessing(
|
||||
@@ -964,7 +981,8 @@ describe('AI Service (Server)', () => {
|
||||
filename: 'upload.jpg',
|
||||
originalname: 'orig.jpg',
|
||||
} as Express.Multer.File; // This was a duplicate, fixed.
|
||||
const mockProfile = { user: { user_id: 'u1' } } as UserProfile;
|
||||
const mockProfile = createMockUserProfile({ user: { user_id: 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11' } });
|
||||
|
||||
|
||||
beforeEach(() => {
|
||||
// Default success mocks. Use createMockFlyer for a more complete mock.
|
||||
@@ -974,8 +992,8 @@ describe('AI Service (Server)', () => {
|
||||
flyer: {
|
||||
flyer_id: 100,
|
||||
file_name: 'orig.jpg',
|
||||
image_url: '/flyer-images/upload.jpg',
|
||||
icon_url: '/flyer-images/icons/icon.jpg',
|
||||
image_url: `${baseUrl}/flyer-images/upload.jpg`,
|
||||
icon_url: `${baseUrl}/flyer-images/icons/icon.jpg`,
|
||||
checksum: 'mock-checksum-123',
|
||||
store_name: 'Mock Store',
|
||||
valid_from: null,
|
||||
@@ -983,7 +1001,7 @@ describe('AI Service (Server)', () => {
|
||||
store_address: null,
|
||||
item_count: 0,
|
||||
status: 'processed',
|
||||
uploaded_by: 'u1',
|
||||
uploaded_by: mockProfile.user.user_id,
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
} as MockFlyer, // Use the more specific MockFlyer type
|
||||
@@ -1118,7 +1136,7 @@ describe('AI Service (Server)', () => {
|
||||
expect(dbModule.adminRepo.logActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'flyer_processed',
|
||||
userId: 'u1',
|
||||
userId: mockProfile.user.user_id,
|
||||
}),
|
||||
mockLoggerInstance,
|
||||
);
|
||||
|
||||
@@ -879,11 +879,27 @@ async enqueueFlyerProcessing(
|
||||
|
||||
const iconsDir = path.join(path.dirname(file.path), 'icons');
|
||||
const iconFileName = await generateFlyerIcon(file.path, iconsDir, logger);
|
||||
const iconUrl = `/flyer-images/icons/${iconFileName}`;
|
||||
|
||||
// Construct proper URLs including protocol and host to satisfy DB constraints.
|
||||
let baseUrl = (process.env.FRONTEND_URL || process.env.BASE_URL || '').trim();
|
||||
if (!baseUrl || !baseUrl.startsWith('http')) {
|
||||
const port = process.env.PORT || 3000;
|
||||
const fallbackUrl = `http://localhost:${port}`;
|
||||
if (baseUrl) {
|
||||
logger.warn(
|
||||
`FRONTEND_URL/BASE_URL is invalid or incomplete ('${baseUrl}'). Falling back to default local URL: ${fallbackUrl}`,
|
||||
);
|
||||
}
|
||||
baseUrl = fallbackUrl;
|
||||
}
|
||||
baseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
|
||||
|
||||
const iconUrl = `${baseUrl}/flyer-images/icons/${iconFileName}`;
|
||||
const imageUrl = `${baseUrl}/flyer-images/${file.filename}`;
|
||||
|
||||
const flyerData: FlyerInsert = {
|
||||
file_name: originalFileName,
|
||||
image_url: `/flyer-images/${file.filename}`,
|
||||
image_url: imageUrl,
|
||||
icon_url: iconUrl,
|
||||
checksum: checksum,
|
||||
store_name: storeName,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// src/services/db/errors.db.test.ts
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import type { Logger } from 'pino';
|
||||
import {
|
||||
DatabaseError,
|
||||
UniqueConstraintError,
|
||||
@@ -7,8 +8,15 @@ import {
|
||||
NotFoundError,
|
||||
ValidationError,
|
||||
FileUploadError,
|
||||
NotNullConstraintError,
|
||||
CheckConstraintError,
|
||||
InvalidTextRepresentationError,
|
||||
NumericValueOutOfRangeError,
|
||||
handleDbError,
|
||||
} from './errors.db';
|
||||
|
||||
vi.mock('./logger.server');
|
||||
|
||||
describe('Custom Database and Application Errors', () => {
|
||||
describe('DatabaseError', () => {
|
||||
it('should create a generic database error with a message and status', () => {
|
||||
@@ -114,4 +122,161 @@ describe('Custom Database and Application Errors', () => {
|
||||
expect(error.name).toBe('FileUploadError');
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotNullConstraintError', () => {
|
||||
it('should create an error with a default message and status 400', () => {
|
||||
const error = new NotNullConstraintError();
|
||||
expect(error).toBeInstanceOf(DatabaseError);
|
||||
expect(error.message).toBe('A required field was left null.');
|
||||
expect(error.status).toBe(400);
|
||||
expect(error.name).toBe('NotNullConstraintError');
|
||||
});
|
||||
|
||||
it('should create an error with a custom message', () => {
|
||||
const message = 'Email cannot be null.';
|
||||
const error = new NotNullConstraintError(message);
|
||||
expect(error.message).toBe(message);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CheckConstraintError', () => {
|
||||
it('should create an error with a default message and status 400', () => {
|
||||
const error = new CheckConstraintError();
|
||||
expect(error).toBeInstanceOf(DatabaseError);
|
||||
expect(error.message).toBe('A check constraint was violated.');
|
||||
expect(error.status).toBe(400);
|
||||
expect(error.name).toBe('CheckConstraintError');
|
||||
});
|
||||
|
||||
it('should create an error with a custom message', () => {
|
||||
const message = 'Price must be positive.';
|
||||
const error = new CheckConstraintError(message);
|
||||
expect(error.message).toBe(message);
|
||||
});
|
||||
});
|
||||
|
||||
describe('InvalidTextRepresentationError', () => {
|
||||
it('should create an error with a default message and status 400', () => {
|
||||
const error = new InvalidTextRepresentationError();
|
||||
expect(error).toBeInstanceOf(DatabaseError);
|
||||
expect(error.message).toBe('A value has an invalid format for its data type.');
|
||||
expect(error.status).toBe(400);
|
||||
expect(error.name).toBe('InvalidTextRepresentationError');
|
||||
});
|
||||
|
||||
it('should create an error with a custom message', () => {
|
||||
const message = 'Invalid input syntax for type integer: "abc"';
|
||||
const error = new InvalidTextRepresentationError(message);
|
||||
expect(error.message).toBe(message);
|
||||
});
|
||||
});
|
||||
|
||||
describe('NumericValueOutOfRangeError', () => {
|
||||
it('should create an error with a default message and status 400', () => {
|
||||
const error = new NumericValueOutOfRangeError();
|
||||
expect(error).toBeInstanceOf(DatabaseError);
|
||||
expect(error.message).toBe('A numeric value is out of the allowed range.');
|
||||
expect(error.status).toBe(400);
|
||||
expect(error.name).toBe('NumericValueOutOfRangeError');
|
||||
});
|
||||
|
||||
it('should create an error with a custom message', () => {
|
||||
const message = 'Value too large for type smallint.';
|
||||
const error = new NumericValueOutOfRangeError(message);
|
||||
expect(error.message).toBe(message);
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleDbError', () => {
|
||||
const mockLogger = {
|
||||
error: vi.fn(),
|
||||
} as unknown as Logger;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should re-throw existing DatabaseError instances without logging', () => {
|
||||
const notFound = new NotFoundError('Test not found');
|
||||
expect(() => handleDbError(notFound, mockLogger, 'msg', {})).toThrow(notFound);
|
||||
expect(mockLogger.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should throw UniqueConstraintError for code 23505', () => {
|
||||
const dbError = new Error('duplicate key');
|
||||
(dbError as any).code = '23505';
|
||||
expect(() =>
|
||||
handleDbError(dbError, mockLogger, 'msg', {}, { uniqueMessage: 'custom unique' }),
|
||||
).toThrow('custom unique');
|
||||
});
|
||||
|
||||
it('should throw ForeignKeyConstraintError for code 23503', () => {
|
||||
const dbError = new Error('fk violation');
|
||||
(dbError as any).code = '23503';
|
||||
expect(() =>
|
||||
handleDbError(dbError, mockLogger, 'msg', {}, { fkMessage: 'custom fk' }),
|
||||
).toThrow('custom fk');
|
||||
});
|
||||
|
||||
it('should throw NotNullConstraintError for code 23502', () => {
|
||||
const dbError = new Error('not null violation');
|
||||
(dbError as any).code = '23502';
|
||||
expect(() =>
|
||||
handleDbError(dbError, mockLogger, 'msg', {}, { notNullMessage: 'custom not null' }),
|
||||
).toThrow('custom not null');
|
||||
});
|
||||
|
||||
it('should throw CheckConstraintError for code 23514', () => {
|
||||
const dbError = new Error('check violation');
|
||||
(dbError as any).code = '23514';
|
||||
expect(() =>
|
||||
handleDbError(dbError, mockLogger, 'msg', {}, { checkMessage: 'custom check' }),
|
||||
).toThrow('custom check');
|
||||
});
|
||||
|
||||
it('should throw InvalidTextRepresentationError for code 22P02', () => {
|
||||
const dbError = new Error('invalid text');
|
||||
(dbError as any).code = '22P02';
|
||||
expect(() =>
|
||||
handleDbError(dbError, mockLogger, 'msg', {}, { invalidTextMessage: 'custom invalid text' }),
|
||||
).toThrow('custom invalid text');
|
||||
});
|
||||
|
||||
it('should throw NumericValueOutOfRangeError for code 22003', () => {
|
||||
const dbError = new Error('out of range');
|
||||
(dbError as any).code = '22003';
|
||||
expect(() =>
|
||||
handleDbError(
|
||||
dbError,
|
||||
mockLogger,
|
||||
'msg',
|
||||
{},
|
||||
{ numericOutOfRangeMessage: 'custom out of range' },
|
||||
),
|
||||
).toThrow('custom out of range');
|
||||
});
|
||||
|
||||
it('should throw a generic Error with a default message', () => {
|
||||
const genericError = new Error('Something else happened');
|
||||
expect(() =>
|
||||
handleDbError(genericError, mockLogger, 'msg', {}, { defaultMessage: 'Oops' }),
|
||||
).toThrow('Oops');
|
||||
expect(mockLogger.error).toHaveBeenCalledWith({ err: genericError }, 'msg');
|
||||
});
|
||||
|
||||
it('should throw a generic Error with a constructed message using entityName', () => {
|
||||
const genericError = new Error('Something else happened');
|
||||
expect(() =>
|
||||
handleDbError(genericError, mockLogger, 'msg', {}, { entityName: 'User' }),
|
||||
).toThrow('Failed to perform operation on User.');
|
||||
});
|
||||
|
||||
it('should throw a generic Error with a constructed message using "database" as a fallback', () => {
|
||||
const genericError = new Error('Something else happened');
|
||||
// No defaultMessage or entityName provided
|
||||
expect(() => handleDbError(genericError, mockLogger, 'msg', {}, {})).toThrow(
|
||||
'Failed to perform operation on database.',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,7 +12,12 @@ import {
|
||||
vi.unmock('./flyer.db');
|
||||
|
||||
import { FlyerRepository, createFlyerAndItems } from './flyer.db';
|
||||
import { UniqueConstraintError, ForeignKeyConstraintError, NotFoundError } from './errors.db';
|
||||
import {
|
||||
UniqueConstraintError,
|
||||
ForeignKeyConstraintError,
|
||||
NotFoundError,
|
||||
CheckConstraintError,
|
||||
} from './errors.db';
|
||||
import type {
|
||||
FlyerInsert,
|
||||
FlyerItemInsert,
|
||||
@@ -126,8 +131,8 @@ describe('Flyer DB Service', () => {
|
||||
it('should execute an INSERT query and return the new flyer', async () => {
|
||||
const flyerData: FlyerDbInsert = {
|
||||
file_name: 'test.jpg',
|
||||
image_url: '/images/test.jpg',
|
||||
icon_url: '/images/icons/test.jpg',
|
||||
image_url: 'http://localhost:3001/images/test.jpg',
|
||||
icon_url: 'http://localhost:3001/images/icons/test.jpg',
|
||||
checksum: 'checksum123',
|
||||
store_id: 1,
|
||||
valid_from: '2024-01-01',
|
||||
@@ -135,7 +140,8 @@ describe('Flyer DB Service', () => {
|
||||
store_address: '123 Test St',
|
||||
status: 'processed',
|
||||
item_count: 10,
|
||||
uploaded_by: 'user-1',
|
||||
// Use a valid UUID format for the foreign key.
|
||||
uploaded_by: 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',
|
||||
};
|
||||
const mockFlyer = createMockFlyer({ ...flyerData, flyer_id: 1 });
|
||||
mockPoolInstance.query.mockResolvedValue({ rows: [mockFlyer] });
|
||||
@@ -148,8 +154,8 @@ describe('Flyer DB Service', () => {
|
||||
expect.stringContaining('INSERT INTO flyers'),
|
||||
[
|
||||
'test.jpg',
|
||||
'/images/test.jpg',
|
||||
'/images/icons/test.jpg',
|
||||
'http://localhost:3001/images/test.jpg',
|
||||
'http://localhost:3001/images/icons/test.jpg',
|
||||
'checksum123',
|
||||
1,
|
||||
'2024-01-01',
|
||||
@@ -157,7 +163,7 @@ describe('Flyer DB Service', () => {
|
||||
'123 Test St',
|
||||
'processed',
|
||||
10,
|
||||
'user-1',
|
||||
'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',
|
||||
],
|
||||
);
|
||||
});
|
||||
@@ -193,6 +199,48 @@ describe('Flyer DB Service', () => {
|
||||
'Database error in insertFlyer',
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw CheckConstraintError for invalid checksum format', async () => {
|
||||
const flyerData: FlyerDbInsert = { checksum: 'short' } as FlyerDbInsert;
|
||||
const dbError = new Error('violates check constraint "flyers_checksum_check"');
|
||||
(dbError as Error & { code: string }).code = '23514'; // Check constraint violation
|
||||
mockPoolInstance.query.mockRejectedValue(dbError);
|
||||
|
||||
await expect(flyerRepo.insertFlyer(flyerData, mockLogger)).rejects.toThrow(
|
||||
CheckConstraintError,
|
||||
);
|
||||
await expect(flyerRepo.insertFlyer(flyerData, mockLogger)).rejects.toThrow(
|
||||
'The provided checksum is invalid or does not meet format requirements (e.g., must be a 64-character SHA-256 hash).',
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw CheckConstraintError for invalid status', async () => {
|
||||
const flyerData: FlyerDbInsert = { status: 'invalid_status' } as any;
|
||||
const dbError = new Error('violates check constraint "flyers_status_check"');
|
||||
(dbError as Error & { code: string }).code = '23514';
|
||||
mockPoolInstance.query.mockRejectedValue(dbError);
|
||||
|
||||
await expect(flyerRepo.insertFlyer(flyerData, mockLogger)).rejects.toThrow(
|
||||
CheckConstraintError,
|
||||
);
|
||||
await expect(flyerRepo.insertFlyer(flyerData, mockLogger)).rejects.toThrow(
|
||||
'Invalid status provided for flyer.',
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw CheckConstraintError for invalid URL format', async () => {
|
||||
const flyerData: FlyerDbInsert = { image_url: 'not-a-url' } as FlyerDbInsert;
|
||||
const dbError = new Error('violates check constraint "url_check"');
|
||||
(dbError as Error & { code: string }).code = '23514';
|
||||
mockPoolInstance.query.mockRejectedValue(dbError);
|
||||
|
||||
await expect(flyerRepo.insertFlyer(flyerData, mockLogger)).rejects.toThrow(
|
||||
CheckConstraintError,
|
||||
);
|
||||
await expect(flyerRepo.insertFlyer(flyerData, mockLogger)).rejects.toThrow(
|
||||
'Invalid URL format provided for image or icon.',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('insertFlyerItems', () => {
|
||||
@@ -329,11 +377,16 @@ describe('Flyer DB Service', () => {
|
||||
// Mock the withTransaction to execute the callback with a mock client
|
||||
vi.mocked(withTransaction).mockImplementation(async (callback) => {
|
||||
const mockClient = { query: vi.fn() };
|
||||
// Mock the sequence of calls within the transaction
|
||||
// Mock the sequence of 4 calls within the transaction
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [{ store_id: 1 }] }) // findOrCreateStore
|
||||
.mockResolvedValueOnce({ rows: [mockFlyer] }) // insertFlyer
|
||||
.mockResolvedValueOnce({ rows: mockItems }); // insertFlyerItems
|
||||
// 1. findOrCreateStore: INSERT ... ON CONFLICT
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 })
|
||||
// 2. findOrCreateStore: SELECT store_id
|
||||
.mockResolvedValueOnce({ rows: [{ store_id: 1 }] })
|
||||
// 3. insertFlyer
|
||||
.mockResolvedValueOnce({ rows: [mockFlyer] })
|
||||
// 4. insertFlyerItems
|
||||
.mockResolvedValueOnce({ rows: mockItems });
|
||||
return callback(mockClient as unknown as PoolClient);
|
||||
});
|
||||
|
||||
@@ -348,56 +401,54 @@ describe('Flyer DB Service', () => {
|
||||
// Verify the individual functions were called with the client
|
||||
const callback = (vi.mocked(withTransaction) as Mock).mock.calls[0][0];
|
||||
const mockClient = { query: vi.fn() };
|
||||
// Set up the same mock sequence for verification
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [{ store_id: 1 }] })
|
||||
.mockResolvedValueOnce({ rows: [mockFlyer] })
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // findOrCreateStore 1
|
||||
.mockResolvedValueOnce({ rows: [{ store_id: 1 }] }) // findOrCreateStore 2
|
||||
.mockResolvedValueOnce({ rows: [mockFlyer] }) // insertFlyer
|
||||
.mockResolvedValueOnce({ rows: mockItems });
|
||||
await callback(mockClient as unknown as PoolClient);
|
||||
|
||||
// findOrCreateStore assertions
|
||||
expect(mockClient.query).toHaveBeenCalledWith(
|
||||
expect.stringContaining('SELECT store_id FROM public.stores'),
|
||||
'INSERT INTO public.stores (name) VALUES ($1) ON CONFLICT (name) DO NOTHING',
|
||||
['Transaction Store'],
|
||||
);
|
||||
expect(mockClient.query).toHaveBeenCalledWith(
|
||||
'SELECT store_id FROM public.stores WHERE name = $1',
|
||||
['Transaction Store'],
|
||||
);
|
||||
// insertFlyer assertion
|
||||
expect(mockClient.query).toHaveBeenCalledWith(
|
||||
expect.stringContaining('INSERT INTO flyers'),
|
||||
expect.any(Array),
|
||||
);
|
||||
// insertFlyerItems assertion
|
||||
expect(mockClient.query).toHaveBeenCalledWith(
|
||||
expect.stringContaining('INSERT INTO flyer_items'),
|
||||
expect.any(Array),
|
||||
);
|
||||
});
|
||||
|
||||
it('should ROLLBACK the transaction if an error occurs', async () => {
|
||||
it('should log and re-throw an error if the transaction fails', async () => {
|
||||
const flyerData: FlyerInsert = {
|
||||
file_name: 'fail.jpg',
|
||||
store_name: 'Fail Store',
|
||||
} as FlyerInsert;
|
||||
const itemsData: FlyerItemInsert[] = [{ item: 'Failing Item' } as FlyerItemInsert];
|
||||
const dbError = new Error('DB connection lost');
|
||||
const transactionError = new Error('Underlying transaction failed');
|
||||
|
||||
// Mock withTransaction to simulate a failure during the callback
|
||||
vi.mocked(withTransaction).mockImplementation(async (callback) => {
|
||||
const mockClient = { query: vi.fn() };
|
||||
mockClient.query
|
||||
.mockResolvedValueOnce({ rows: [{ store_id: 1 }] }) // findOrCreateStore
|
||||
.mockRejectedValueOnce(dbError); // insertFlyer fails
|
||||
// The withTransaction helper will catch this and roll back.
|
||||
// Since insertFlyer wraps the DB error, we expect the wrapped error message here.
|
||||
await expect(callback(mockClient as unknown as PoolClient)).rejects.toThrow(
|
||||
'Failed to insert flyer into database.',
|
||||
);
|
||||
// re-throw because withTransaction re-throws (simulating the wrapped error propagating up)
|
||||
throw new Error('Failed to insert flyer into database.');
|
||||
});
|
||||
// Mock withTransaction to reject directly
|
||||
vi.mocked(withTransaction).mockRejectedValue(transactionError);
|
||||
|
||||
// The transactional function re-throws the original error from the failed step.
|
||||
// Since insertFlyer wraps errors, we expect the wrapped error message.
|
||||
// Expect the createFlyerAndItems function to reject with the same error
|
||||
await expect(createFlyerAndItems(flyerData, itemsData, mockLogger)).rejects.toThrow(
|
||||
'Failed to insert flyer into database.',
|
||||
transactionError,
|
||||
);
|
||||
// The error object passed to the logger will be the wrapped Error object, not the original dbError
|
||||
|
||||
// Verify that the error was logged before being re-thrown
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(
|
||||
{ err: expect.any(Error) },
|
||||
{ err: transactionError },
|
||||
'Database transaction error in createFlyerAndItems',
|
||||
);
|
||||
expect(withTransaction).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -86,6 +86,11 @@ export class FlyerRepository {
|
||||
flyerData.uploaded_by ?? null, // $11
|
||||
];
|
||||
|
||||
logger.debug(
|
||||
{ query, values },
|
||||
'[DB insertFlyer] Executing insert with the following values.',
|
||||
);
|
||||
|
||||
const result = await this.db.query<Flyer>(query, values);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
@@ -154,6 +159,11 @@ export class FlyerRepository {
|
||||
RETURNING *;
|
||||
`;
|
||||
|
||||
logger.debug(
|
||||
{ query, values },
|
||||
'[DB insertFlyerItems] Executing bulk insert with the following values.',
|
||||
);
|
||||
|
||||
const result = await this.db.query<FlyerItem>(query, values);
|
||||
return result.rows;
|
||||
} catch (error) {
|
||||
|
||||
@@ -237,6 +237,13 @@ describe('Shopping DB Service', () => {
|
||||
});
|
||||
|
||||
it('should throw an error if both masterItemId and customItemName are missing', async () => {
|
||||
// This test covers line 185 in shopping.db.ts
|
||||
await expect(shoppingRepo.addShoppingListItem(1, 'user-1', {}, mockLogger)).rejects.toThrow(
|
||||
'Either masterItemId or customItemName must be provided.',
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw an error if no item data is provided', async () => {
|
||||
await expect(shoppingRepo.addShoppingListItem(1, 'user-1', {}, mockLogger)).rejects.toThrow(
|
||||
'Either masterItemId or customItemName must be provided.',
|
||||
);
|
||||
@@ -251,6 +258,15 @@ describe('Shopping DB Service', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw an error if provided updates are not valid fields', async () => {
|
||||
// This test covers line 362 in shopping.db.ts
|
||||
const updates = { invalid_field: 'some_value' };
|
||||
await expect(
|
||||
shoppingRepo.updateShoppingListItem(1, 'user-1', updates as any, mockLogger),
|
||||
).rejects.toThrow('No valid fields to update.');
|
||||
expect(mockPoolInstance.query).not.toHaveBeenCalled(); // No DB query should be made
|
||||
});
|
||||
|
||||
it('should throw a generic error if the database query fails', async () => {
|
||||
const dbError = new Error('DB Connection Error');
|
||||
mockPoolInstance.query.mockRejectedValue(dbError);
|
||||
|
||||
@@ -678,14 +678,17 @@ describe('User DB Service', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should not throw an error if the database query fails', async () => {
|
||||
mockPoolInstance.query.mockRejectedValue(new Error('DB Error'));
|
||||
it('should log an error but not throw if the database query fails', async () => {
|
||||
const dbError = new Error('DB Error');
|
||||
mockPoolInstance.query.mockRejectedValue(dbError);
|
||||
|
||||
// The function is designed to swallow errors, so we expect it to resolve.
|
||||
await expect(userRepo.deleteRefreshToken('a-token', mockLogger)).resolves.toBeUndefined();
|
||||
|
||||
// We can still check that the query was attempted.
|
||||
expect(mockPoolInstance.query).toHaveBeenCalled();
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(
|
||||
{ err: expect.any(Error) },
|
||||
{ err: dbError },
|
||||
'Database error in deleteRefreshToken',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -106,7 +106,7 @@ export class FlyerDataTransformer {
|
||||
// Defensively handle the userId. An empty string ('') is not a valid UUID,
|
||||
// but `null` is. This ensures that any falsy value for userId (undefined, null, '')
|
||||
// is converted to `null` for the database, preventing a 22P02 error.
|
||||
uploaded_by: userId || null,
|
||||
uploaded_by: userId ? userId : null,
|
||||
status: needsReview ? 'needs_review' : 'processed',
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,10 @@ import { ValidationError, NotFoundError } from './db/errors.db';
|
||||
import type { Job } from 'bullmq';
|
||||
import type { TokenCleanupJobData } from '../types/job-data';
|
||||
|
||||
// Un-mock the service under test to ensure we are testing the real implementation,
|
||||
// not the global mock from `tests/setup/tests-setup-unit.ts`.
|
||||
vi.unmock('./userService');
|
||||
|
||||
// --- Hoisted Mocks ---
|
||||
const mocks = vi.hoisted(() => {
|
||||
// Create mock implementations for the repository methods we'll be using.
|
||||
@@ -212,9 +216,12 @@ describe('UserService', () => {
|
||||
describe('updateUserAvatar', () => {
|
||||
it('should construct avatar URL and update profile', async () => {
|
||||
const { logger } = await import('./logger.server');
|
||||
const testBaseUrl = 'http://localhost:3001';
|
||||
vi.stubEnv('FRONTEND_URL', testBaseUrl);
|
||||
|
||||
const userId = 'user-123';
|
||||
const file = { filename: 'avatar.jpg' } as Express.Multer.File;
|
||||
const expectedUrl = '/uploads/avatars/avatar.jpg';
|
||||
const expectedUrl = `${testBaseUrl}/uploads/avatars/avatar.jpg`;
|
||||
|
||||
mocks.mockUpdateUserProfile.mockResolvedValue({} as any);
|
||||
|
||||
@@ -225,6 +232,8 @@ describe('UserService', () => {
|
||||
{ avatar_url: expectedUrl },
|
||||
logger,
|
||||
);
|
||||
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -87,7 +87,21 @@ class UserService {
|
||||
* @returns The updated user profile.
|
||||
*/
|
||||
async updateUserAvatar(userId: string, file: Express.Multer.File, logger: Logger): Promise<Profile> {
|
||||
const avatarUrl = `/uploads/avatars/${file.filename}`;
|
||||
// Construct proper URLs including protocol and host to satisfy DB constraints.
|
||||
let baseUrl = (process.env.FRONTEND_URL || process.env.BASE_URL || '').trim();
|
||||
if (!baseUrl || !baseUrl.startsWith('http')) {
|
||||
const port = process.env.PORT || 3000;
|
||||
const fallbackUrl = `http://localhost:${port}`;
|
||||
if (baseUrl) {
|
||||
logger.warn(
|
||||
`FRONTEND_URL/BASE_URL is invalid or incomplete ('${baseUrl}'). Falling back to default local URL: ${fallbackUrl}`,
|
||||
);
|
||||
}
|
||||
baseUrl = fallbackUrl;
|
||||
}
|
||||
baseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
|
||||
|
||||
const avatarUrl = `${baseUrl}/uploads/avatars/${file.filename}`;
|
||||
return db.userRepo.updateUserProfile(
|
||||
userId,
|
||||
{ avatar_url: avatarUrl },
|
||||
|
||||
@@ -174,10 +174,19 @@ describe('Authentication E2E Flow', () => {
|
||||
expect(registerResponse.status).toBe(201);
|
||||
createdUserIds.push(registerData.userprofile.user.user_id);
|
||||
|
||||
// Add a small delay to mitigate potential DB replication lag or race conditions
|
||||
// in the test environment. Increased from 2s to 5s to improve stability.
|
||||
// The root cause is likely environmental slowness in the CI database.
|
||||
await new Promise((resolve) => setTimeout(resolve, 5000));
|
||||
// Instead of a fixed delay, poll by attempting to log in. This is more robust
|
||||
// and confirms the user record is committed and readable by subsequent transactions.
|
||||
let loginSuccess = false;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
// Poll for up to 10 seconds
|
||||
const loginResponse = await apiClient.loginUser(email, TEST_PASSWORD, false);
|
||||
if (loginResponse.ok) {
|
||||
loginSuccess = true;
|
||||
break;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
expect(loginSuccess, 'User should be able to log in after registration before password reset is attempted.').toBe(true);
|
||||
|
||||
// Act 1: Request a password reset.
|
||||
// The test environment returns the token directly in the response for E2E testing.
|
||||
|
||||
@@ -1,48 +1,59 @@
|
||||
// src/tests/integration/db.integration.test.ts
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import * as db from '../../services/db/index.db';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { getPool } from '../../services/db/connection.db';
|
||||
import { logger } from '../../services/logger.server';
|
||||
import type { UserProfile } from '../../types';
|
||||
import { cleanupDb } from '../utils/cleanup';
|
||||
|
||||
describe('Database Service Integration Tests', () => {
|
||||
it('should create a new user and be able to find them by email', async ({ onTestFinished }) => {
|
||||
let testUser: UserProfile;
|
||||
let testUserEmail: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Arrange: Use a unique email for each test run to ensure isolation.
|
||||
const email = `test.user-${Date.now()}@example.com`;
|
||||
testUserEmail = `test.user-${Date.now()}@example.com`;
|
||||
const password = 'password123';
|
||||
const fullName = 'Test User';
|
||||
const saltRounds = 10;
|
||||
const passwordHash = await bcrypt.hash(password, saltRounds);
|
||||
|
||||
// Ensure the created user is cleaned up after this specific test finishes.
|
||||
onTestFinished(async () => {
|
||||
await getPool().query('DELETE FROM public.users WHERE email = $1', [email]);
|
||||
});
|
||||
|
||||
// Act: Call the createUser function
|
||||
const createdUser = await db.userRepo.createUser(
|
||||
email,
|
||||
testUser = await db.userRepo.createUser(
|
||||
testUserEmail,
|
||||
passwordHash,
|
||||
{ full_name: fullName },
|
||||
logger,
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Ensure the created user is cleaned up after each test.
|
||||
if (testUser?.user.user_id) {
|
||||
await cleanupDb({ userIds: [testUser.user.user_id] });
|
||||
}
|
||||
});
|
||||
|
||||
it('should create a new user and have a corresponding profile', async () => {
|
||||
// Assert: Check that the user was created with the correct details
|
||||
expect(createdUser).toBeDefined();
|
||||
expect(createdUser.user.email).toBe(email); // This is correct
|
||||
expect(createdUser.user.user_id).toBeTypeOf('string');
|
||||
expect(testUser).toBeDefined();
|
||||
expect(testUser.user.email).toBe(testUserEmail);
|
||||
expect(testUser.user.user_id).toBeTypeOf('string');
|
||||
|
||||
// Also, verify the profile was created by the trigger
|
||||
const profile = await db.userRepo.findUserProfileById(testUser.user.user_id, logger);
|
||||
expect(profile).toBeDefined();
|
||||
expect(profile?.full_name).toBe('Test User');
|
||||
});
|
||||
|
||||
it('should be able to find the created user by email', async () => {
|
||||
// Act: Try to find the user we just created
|
||||
const foundUser = await db.userRepo.findUserByEmail(email, logger);
|
||||
const foundUser = await db.userRepo.findUserByEmail(testUserEmail, logger);
|
||||
|
||||
// Assert: Check that the found user matches the created user
|
||||
expect(foundUser).toBeDefined();
|
||||
expect(foundUser?.user_id).toBe(createdUser.user.user_id);
|
||||
expect(foundUser?.email).toBe(email);
|
||||
|
||||
// Also, verify the profile was created by the trigger
|
||||
const profile = await db.userRepo.findUserProfileById(createdUser.user.user_id, logger);
|
||||
expect(profile).toBeDefined();
|
||||
expect(profile?.full_name).toBe(fullName);
|
||||
expect(foundUser?.user_id).toBe(testUser.user.user_id);
|
||||
expect(foundUser?.email).toBe(testUserEmail);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ import { cleanupFiles } from '../utils/cleanupFiles';
|
||||
import piexif from 'piexifjs';
|
||||
import exifParser from 'exif-parser';
|
||||
import sharp from 'sharp';
|
||||
import { createFlyerAndItems } from '../../services/db/flyer.db';
|
||||
|
||||
|
||||
/**
|
||||
@@ -23,8 +24,30 @@ import sharp from 'sharp';
|
||||
|
||||
const request = supertest(app);
|
||||
|
||||
// Import the mocked service to control its behavior in tests.
|
||||
import { aiService } from '../../services/aiService.server';
|
||||
const { mockExtractCoreData } = vi.hoisted(() => ({
|
||||
mockExtractCoreData: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock the AI service to prevent real API calls during integration tests.
|
||||
// This is crucial for making the tests reliable and fast. We don't want to
|
||||
// depend on the external Gemini API.
|
||||
vi.mock('../../services/aiService.server', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../services/aiService.server')>();
|
||||
// To preserve the class instance methods of `aiService`, we must modify the
|
||||
// instance directly rather than creating a new plain object with spread syntax.
|
||||
actual.aiService.extractCoreDataFromFlyerImage = mockExtractCoreData;
|
||||
return actual;
|
||||
});
|
||||
|
||||
// Mock the database service to allow for simulating DB failures.
|
||||
// By default, it will use the real implementation.
|
||||
vi.mock('../../services/db/flyer.db', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../services/db/flyer.db')>();
|
||||
return {
|
||||
...actual,
|
||||
createFlyerAndItems: vi.fn().mockImplementation(actual.createFlyerAndItems),
|
||||
};
|
||||
});
|
||||
|
||||
describe('Flyer Processing Background Job Integration Test', () => {
|
||||
const createdUserIds: string[] = [];
|
||||
@@ -32,23 +55,21 @@ describe('Flyer Processing Background Job Integration Test', () => {
|
||||
const createdFilePaths: string[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
// This setup is now simpler as the worker handles fetching master items.
|
||||
// Setup default mock response for AI service
|
||||
const mockItems: ExtractedFlyerItem[] = [
|
||||
{
|
||||
item: 'Mocked Integration Item',
|
||||
price_display: '$1.99',
|
||||
price_in_cents: 199,
|
||||
quantity: 'each',
|
||||
category_name: 'Mock Category',
|
||||
},
|
||||
];
|
||||
vi.spyOn(aiService, 'extractCoreDataFromFlyerImage').mockResolvedValue({
|
||||
// Setup default mock response for the AI service's extractCoreDataFromFlyerImage method.
|
||||
mockExtractCoreData.mockResolvedValue({
|
||||
store_name: 'Mock Store',
|
||||
valid_from: null,
|
||||
valid_to: null,
|
||||
store_address: null,
|
||||
items: mockItems,
|
||||
items: [
|
||||
{
|
||||
item: 'Mocked Integration Item',
|
||||
price_display: '$1.99',
|
||||
price_in_cents: 199,
|
||||
quantity: 'each',
|
||||
category_name: 'Mock Category',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -165,11 +186,6 @@ describe('Flyer Processing Background Job Integration Test', () => {
|
||||
});
|
||||
createdUserIds.push(authUser.user.user_id); // Track for cleanup
|
||||
|
||||
// Use a cleanup function to delete the user even if the test fails.
|
||||
onTestFinished(async () => {
|
||||
await getPool().query('DELETE FROM public.users WHERE user_id = $1', [authUser.user.user_id]);
|
||||
});
|
||||
|
||||
// Act & Assert
|
||||
await runBackgroundProcessingTest(authUser, token);
|
||||
}, 240000); // Increase timeout to 240 seconds for this long-running test
|
||||
@@ -347,4 +363,162 @@ describe('Flyer Processing Background Job Integration Test', () => {
|
||||
},
|
||||
240000,
|
||||
);
|
||||
|
||||
it(
|
||||
'should handle a failure from the AI service gracefully',
|
||||
async () => {
|
||||
// Arrange: Mock the AI service to throw an error for this specific test.
|
||||
const aiError = new Error('AI model failed to extract data.');
|
||||
mockExtractCoreData.mockRejectedValueOnce(aiError);
|
||||
|
||||
// Arrange: Prepare a unique flyer file for upload.
|
||||
const imagePath = path.resolve(__dirname, '../assets/test-flyer-image.jpg');
|
||||
const imageBuffer = await fs.readFile(imagePath);
|
||||
const uniqueContent = Buffer.concat([imageBuffer, Buffer.from(`fail-test-${Date.now()}`)]);
|
||||
const uniqueFileName = `ai-fail-test-${Date.now()}.jpg`;
|
||||
const mockImageFile = new File([uniqueContent], uniqueFileName, { type: 'image/jpeg' });
|
||||
const checksum = await generateFileChecksum(mockImageFile);
|
||||
|
||||
// Track created files for cleanup
|
||||
const uploadDir = path.resolve(__dirname, '../../../flyer-images');
|
||||
createdFilePaths.push(path.join(uploadDir, uniqueFileName));
|
||||
|
||||
// Act 1: Upload the file to start the background job.
|
||||
const uploadResponse = await request
|
||||
.post('/api/ai/upload-and-process')
|
||||
.field('checksum', checksum)
|
||||
.attach('flyerFile', uniqueContent, uniqueFileName);
|
||||
|
||||
const { jobId } = uploadResponse.body;
|
||||
expect(jobId).toBeTypeOf('string');
|
||||
|
||||
// Act 2: Poll for the job status until it completes or fails.
|
||||
let jobStatus;
|
||||
const maxRetries = 60;
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
const statusResponse = await request.get(`/api/ai/jobs/${jobId}/status`);
|
||||
jobStatus = statusResponse.body;
|
||||
if (jobStatus.state === 'completed' || jobStatus.state === 'failed') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Assert 1: Check that the job failed.
|
||||
expect(jobStatus?.state).toBe('failed');
|
||||
expect(jobStatus?.failedReason).toContain('AI model failed to extract data.');
|
||||
|
||||
// Assert 2: Verify the flyer was NOT saved in the database.
|
||||
const savedFlyer = await db.flyerRepo.findFlyerByChecksum(checksum, logger);
|
||||
expect(savedFlyer).toBeUndefined();
|
||||
},
|
||||
240000,
|
||||
);
|
||||
|
||||
it(
|
||||
'should handle a database failure during flyer creation',
|
||||
async () => {
|
||||
// Arrange: Mock the database creation function to throw an error for this specific test.
|
||||
const dbError = new Error('DB transaction failed');
|
||||
vi.mocked(createFlyerAndItems).mockRejectedValueOnce(dbError);
|
||||
|
||||
// Arrange: Prepare a unique flyer file for upload.
|
||||
const imagePath = path.resolve(__dirname, '../assets/test-flyer-image.jpg');
|
||||
const imageBuffer = await fs.readFile(imagePath);
|
||||
const uniqueContent = Buffer.concat([imageBuffer, Buffer.from(`db-fail-test-${Date.now()}`)]);
|
||||
const uniqueFileName = `db-fail-test-${Date.now()}.jpg`;
|
||||
const mockImageFile = new File([uniqueContent], uniqueFileName, { type: 'image/jpeg' });
|
||||
const checksum = await generateFileChecksum(mockImageFile);
|
||||
|
||||
// Track created files for cleanup
|
||||
const uploadDir = path.resolve(__dirname, '../../../flyer-images');
|
||||
createdFilePaths.push(path.join(uploadDir, uniqueFileName));
|
||||
|
||||
// Act 1: Upload the file to start the background job.
|
||||
const uploadResponse = await request
|
||||
.post('/api/ai/upload-and-process')
|
||||
.field('checksum', checksum)
|
||||
.attach('flyerFile', uniqueContent, uniqueFileName);
|
||||
|
||||
const { jobId } = uploadResponse.body;
|
||||
expect(jobId).toBeTypeOf('string');
|
||||
|
||||
// Act 2: Poll for the job status until it completes or fails.
|
||||
let jobStatus;
|
||||
const maxRetries = 60;
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
const statusResponse = await request.get(`/api/ai/jobs/${jobId}/status`);
|
||||
jobStatus = statusResponse.body;
|
||||
if (jobStatus.state === 'completed' || jobStatus.state === 'failed') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Assert 1: Check that the job failed.
|
||||
expect(jobStatus?.state).toBe('failed');
|
||||
expect(jobStatus?.failedReason).toContain('DB transaction failed');
|
||||
|
||||
// Assert 2: Verify the flyer was NOT saved in the database.
|
||||
const savedFlyer = await db.flyerRepo.findFlyerByChecksum(checksum, logger);
|
||||
expect(savedFlyer).toBeUndefined();
|
||||
},
|
||||
240000,
|
||||
);
|
||||
|
||||
it(
|
||||
'should NOT clean up temporary files when a job fails, to allow for manual inspection',
|
||||
async () => {
|
||||
// Arrange: Mock the AI service to throw an error, causing the job to fail.
|
||||
const aiError = new Error('Simulated AI failure for cleanup test.');
|
||||
mockExtractCoreData.mockRejectedValueOnce(aiError);
|
||||
|
||||
// Arrange: Prepare a unique flyer file for upload.
|
||||
const imagePath = path.resolve(__dirname, '../assets/test-flyer-image.jpg');
|
||||
const imageBuffer = await fs.readFile(imagePath);
|
||||
const uniqueContent = Buffer.concat([
|
||||
imageBuffer,
|
||||
Buffer.from(`cleanup-fail-test-${Date.now()}`),
|
||||
]);
|
||||
const uniqueFileName = `cleanup-fail-test-${Date.now()}.jpg`;
|
||||
const mockImageFile = new File([uniqueContent], uniqueFileName, { type: 'image/jpeg' });
|
||||
const checksum = await generateFileChecksum(mockImageFile);
|
||||
|
||||
// Track the path of the file that will be created in the uploads directory.
|
||||
const uploadDir = path.resolve(__dirname, '../../../flyer-images');
|
||||
const tempFilePath = path.join(uploadDir, uniqueFileName);
|
||||
createdFilePaths.push(tempFilePath);
|
||||
|
||||
// Act 1: Upload the file to start the background job.
|
||||
const uploadResponse = await request
|
||||
.post('/api/ai/upload-and-process')
|
||||
.field('checksum', checksum)
|
||||
.attach('flyerFile', uniqueContent, uniqueFileName);
|
||||
|
||||
const { jobId } = uploadResponse.body;
|
||||
expect(jobId).toBeTypeOf('string');
|
||||
|
||||
// Act 2: Poll for the job status until it fails.
|
||||
let jobStatus;
|
||||
const maxRetries = 60;
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
const statusResponse = await request.get(`/api/ai/jobs/${jobId}/status`);
|
||||
jobStatus = statusResponse.body;
|
||||
if (jobStatus.state === 'failed') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Assert 1: Check that the job actually failed.
|
||||
expect(jobStatus?.state).toBe('failed');
|
||||
expect(jobStatus?.failedReason).toContain('Simulated AI failure for cleanup test.');
|
||||
|
||||
// Assert 2: Verify the temporary file was NOT deleted.
|
||||
// We check for its existence. If it doesn't exist, fs.access will throw an error.
|
||||
await expect(fs.access(tempFilePath), 'Expected temporary file to exist after job failure, but it was deleted.');
|
||||
},
|
||||
240000,
|
||||
);
|
||||
|
||||
});
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// src/tests/integration/flyer.integration.test.ts
|
||||
import { describe, it, expect, beforeAll } from 'vitest';
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import supertest from 'supertest';
|
||||
import { getPool } from '../../services/db/connection.db';
|
||||
import app from '../../../server';
|
||||
import type { Flyer, FlyerItem } from '../../types';
|
||||
import { cleanupDb } from '../utils/cleanup';
|
||||
|
||||
/**
|
||||
* @vitest-environment node
|
||||
@@ -13,6 +14,7 @@ describe('Public Flyer API Routes Integration Tests', () => {
|
||||
let flyers: Flyer[] = [];
|
||||
// Use a supertest instance for all requests in this file
|
||||
const request = supertest(app);
|
||||
let testStoreId: number;
|
||||
let createdFlyerId: number;
|
||||
|
||||
// Fetch flyers once before all tests in this suite to use in subsequent tests.
|
||||
@@ -21,12 +23,12 @@ describe('Public Flyer API Routes Integration Tests', () => {
|
||||
const storeRes = await getPool().query(
|
||||
`INSERT INTO public.stores (name) VALUES ('Integration Test Store') RETURNING store_id`,
|
||||
);
|
||||
const storeId = storeRes.rows[0].store_id;
|
||||
testStoreId = storeRes.rows[0].store_id;
|
||||
|
||||
const flyerRes = await getPool().query(
|
||||
`INSERT INTO public.flyers (store_id, file_name, image_url, icon_url, item_count, checksum)
|
||||
VALUES ($1, 'integration-test.jpg', 'https://example.com/flyer-images/integration-test.jpg', 'https://example.com/flyer-images/icons/integration-test.jpg', 1, $2) RETURNING flyer_id`,
|
||||
[storeId, `${Date.now().toString(16)}`.padEnd(64, '0')],
|
||||
[testStoreId, `${Date.now().toString(16)}`.padEnd(64, '0')],
|
||||
);
|
||||
createdFlyerId = flyerRes.rows[0].flyer_id;
|
||||
|
||||
@@ -41,6 +43,14 @@ describe('Public Flyer API Routes Integration Tests', () => {
|
||||
flyers = response.body;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
// Clean up the test data created in beforeAll to prevent polluting the test database.
|
||||
await cleanupDb({
|
||||
flyerIds: [createdFlyerId],
|
||||
storeIds: [testStoreId],
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/flyers', () => {
|
||||
it('should return a list of flyers', async () => {
|
||||
// Act: Call the API endpoint using the client function.
|
||||
|
||||
@@ -4,11 +4,13 @@ import supertest from 'supertest';
|
||||
import app from '../../../server';
|
||||
import path from 'path';
|
||||
import fs from 'node:fs/promises';
|
||||
import { getPool } from '../../services/db/connection.db';
|
||||
import { createAndLoginUser } from '../utils/testHelpers';
|
||||
import { generateFileChecksum } from '../../utils/checksum';
|
||||
import * as db from '../../services/db/index.db';
|
||||
import { cleanupDb } from '../utils/cleanup';
|
||||
import { logger } from '../../services/logger.server';
|
||||
import * as imageProcessor from '../../utils/imageProcessor';
|
||||
import type {
|
||||
UserProfile,
|
||||
UserAchievement,
|
||||
@@ -16,6 +18,7 @@ import type {
|
||||
Achievement,
|
||||
ExtractedFlyerItem,
|
||||
} from '../../types';
|
||||
import type { Flyer } from '../../types';
|
||||
import { cleanupFiles } from '../utils/cleanupFiles';
|
||||
|
||||
/**
|
||||
@@ -24,14 +27,36 @@ import { cleanupFiles } from '../utils/cleanupFiles';
|
||||
|
||||
const request = supertest(app);
|
||||
|
||||
// Import the mocked service to control its behavior in tests.
|
||||
import { aiService } from '../../services/aiService.server';
|
||||
const { mockExtractCoreData } = vi.hoisted(() => ({
|
||||
mockExtractCoreData: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock the AI service to prevent real API calls during integration tests.
|
||||
// This is crucial for making the tests reliable and fast. We don't want to
|
||||
// depend on the external Gemini API.
|
||||
vi.mock('../../services/aiService.server', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../services/aiService.server')>();
|
||||
// To preserve the class instance methods of `aiService`, we must modify the
|
||||
// instance directly rather than creating a new plain object with spread syntax.
|
||||
actual.aiService.extractCoreDataFromFlyerImage = mockExtractCoreData;
|
||||
return actual;
|
||||
});
|
||||
|
||||
// Mock the image processor to control icon generation for legacy uploads
|
||||
vi.mock('../../utils/imageProcessor', async () => {
|
||||
const actual = await vi.importActual<typeof imageProcessor>('../../utils/imageProcessor');
|
||||
return {
|
||||
...actual,
|
||||
generateFlyerIcon: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe('Gamification Flow Integration Test', () => {
|
||||
let testUser: UserProfile;
|
||||
let authToken: string;
|
||||
const createdFlyerIds: number[] = [];
|
||||
const createdFilePaths: string[] = [];
|
||||
const createdStoreIds: number[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
// Create a new user specifically for this test suite to ensure a clean slate.
|
||||
@@ -41,26 +66,21 @@ describe('Gamification Flow Integration Test', () => {
|
||||
request,
|
||||
}));
|
||||
|
||||
// Mock the AI service's method to prevent actual API calls during integration tests.
|
||||
// This is crucial for making the integration test reliable. We don't want to
|
||||
// depend on the external Gemini API, which has quotas and can be slow.
|
||||
// By mocking this, we test our application's internal flow:
|
||||
// API -> Queue -> Worker -> DB -> Gamification Logic
|
||||
const mockExtractedItems: ExtractedFlyerItem[] = [
|
||||
{
|
||||
item: 'Integration Test Milk',
|
||||
price_display: '$4.99',
|
||||
price_in_cents: 499,
|
||||
quantity: '2L',
|
||||
category_name: 'Dairy',
|
||||
},
|
||||
];
|
||||
vi.spyOn(aiService, 'extractCoreDataFromFlyerImage').mockResolvedValue({
|
||||
// Setup default mock response for the AI service's extractCoreDataFromFlyerImage method.
|
||||
mockExtractCoreData.mockResolvedValue({
|
||||
store_name: 'Gamification Test Store',
|
||||
valid_from: null,
|
||||
valid_to: null,
|
||||
store_address: null,
|
||||
items: mockExtractedItems,
|
||||
items: [
|
||||
{
|
||||
item: 'Integration Test Milk',
|
||||
price_display: '$4.99',
|
||||
price_in_cents: 499,
|
||||
quantity: '2L',
|
||||
category_name: 'Dairy',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -68,6 +88,7 @@ describe('Gamification Flow Integration Test', () => {
|
||||
await cleanupDb({
|
||||
userIds: testUser ? [testUser.user.user_id] : [],
|
||||
flyerIds: createdFlyerIds,
|
||||
storeIds: createdStoreIds,
|
||||
});
|
||||
await cleanupFiles(createdFilePaths);
|
||||
});
|
||||
@@ -75,6 +96,10 @@ describe('Gamification Flow Integration Test', () => {
|
||||
it(
|
||||
'should award the "First Upload" achievement after a user successfully uploads and processes their first flyer',
|
||||
async () => {
|
||||
// --- Arrange: Stub environment variables for URL generation in the background worker ---
|
||||
const testBaseUrl = 'http://localhost:3001'; // Use a fixed port for predictability
|
||||
vi.stubEnv('FRONTEND_URL', testBaseUrl);
|
||||
|
||||
// --- Arrange: Prepare a unique flyer file for upload ---
|
||||
const imagePath = path.resolve(__dirname, '../assets/test-flyer-image.jpg');
|
||||
const imageBuffer = await fs.readFile(imagePath);
|
||||
@@ -161,7 +186,82 @@ describe('Gamification Flow Integration Test', () => {
|
||||
expect(Number(userOnLeaderboard?.points)).toBeGreaterThanOrEqual(
|
||||
firstUploadAchievement!.points_value,
|
||||
);
|
||||
|
||||
// --- Cleanup ---
|
||||
vi.unstubAllEnvs();
|
||||
},
|
||||
240000, // Increase timeout to 240s to match other long-running processing tests
|
||||
);
|
||||
|
||||
describe('Legacy Flyer Upload', () => {
|
||||
it('should process a legacy upload and save fully qualified URLs to the database', async () => {
|
||||
// --- Arrange ---
|
||||
// 1. Stub environment variables to have a predictable base URL for the test.
|
||||
const testBaseUrl = 'https://cdn.example.com';
|
||||
vi.stubEnv('FRONTEND_URL', testBaseUrl);
|
||||
|
||||
// 2. Mock the icon generator to return a predictable filename.
|
||||
vi.mocked(imageProcessor.generateFlyerIcon).mockResolvedValue('legacy-icon.webp');
|
||||
|
||||
// 3. Prepare a unique file for upload to avoid checksum conflicts.
|
||||
const imagePath = path.resolve(__dirname, '../assets/test-flyer-image.jpg');
|
||||
const imageBuffer = await fs.readFile(imagePath);
|
||||
const uniqueFileName = `legacy-upload-test-${Date.now()}.jpg`;
|
||||
const mockImageFile = new File([imageBuffer], uniqueFileName, { type: 'image/jpeg' });
|
||||
const checksum = await generateFileChecksum(mockImageFile);
|
||||
|
||||
// Track created files for cleanup.
|
||||
const uploadDir = path.resolve(__dirname, '../../../flyer-images');
|
||||
createdFilePaths.push(path.join(uploadDir, uniqueFileName));
|
||||
createdFilePaths.push(path.join(uploadDir, 'icons', 'legacy-icon.webp'));
|
||||
|
||||
// 4. Prepare the legacy payload (body of the request).
|
||||
const storeName = `Legacy Store - ${Date.now()}`;
|
||||
const legacyPayload = {
|
||||
checksum: checksum,
|
||||
extractedData: {
|
||||
store_name: storeName,
|
||||
items: [{ item: 'Legacy Milk', price_in_cents: 250 }],
|
||||
},
|
||||
};
|
||||
|
||||
// --- Act ---
|
||||
// 5. Make the API request.
|
||||
// Note: This assumes a legacy endpoint exists at `/api/ai/upload-legacy`.
|
||||
// This endpoint would be responsible for calling `aiService.processLegacyFlyerUpload`.
|
||||
const response = await request
|
||||
.post('/api/ai/upload-legacy')
|
||||
.set('Authorization', `Bearer ${authToken}`)
|
||||
.field('data', JSON.stringify(legacyPayload))
|
||||
.attach('flyerFile', imageBuffer, uniqueFileName);
|
||||
|
||||
// --- Assert ---
|
||||
// 6. Check for a successful response.
|
||||
expect(response.status).toBe(200);
|
||||
const newFlyer: Flyer = response.body;
|
||||
expect(newFlyer).toBeDefined();
|
||||
expect(newFlyer.flyer_id).toBeTypeOf('number');
|
||||
createdFlyerIds.push(newFlyer.flyer_id); // Add for cleanup.
|
||||
|
||||
// 7. Query the database directly to verify the saved values.
|
||||
const pool = getPool();
|
||||
const dbResult = await pool.query<Flyer>(
|
||||
'SELECT image_url, icon_url, store_id FROM public.flyers WHERE flyer_id = $1',
|
||||
[newFlyer.flyer_id],
|
||||
);
|
||||
|
||||
expect(dbResult.rowCount).toBe(1);
|
||||
const savedFlyer = dbResult.rows[0];
|
||||
// The store_id is guaranteed to exist for a saved flyer, but the generic `Flyer` type
|
||||
// might have it as optional. We use a non-null assertion `!` to satisfy TypeScript.
|
||||
createdStoreIds.push(savedFlyer.store_id!); // Add for cleanup.
|
||||
|
||||
// 8. Assert that the URLs are fully qualified.
|
||||
expect(savedFlyer.image_url).to.equal(`${testBaseUrl}/flyer-images/${uniqueFileName}`);
|
||||
expect(savedFlyer.icon_url).to.equal(`${testBaseUrl}/flyer-images/icons/legacy-icon.webp`);
|
||||
|
||||
// --- Cleanup ---
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -329,6 +329,59 @@ vi.mock('react-hot-toast', () => ({
|
||||
|
||||
// --- Database Service Mocks ---
|
||||
|
||||
// Mock for db/index.db which exports repository instances used by many routes
|
||||
vi.mock('../../services/db/index.db', () => ({
|
||||
userRepo: {
|
||||
findUserProfileById: vi.fn(),
|
||||
updateUserProfile: vi.fn(),
|
||||
updateUserPreferences: vi.fn(),
|
||||
},
|
||||
personalizationRepo: {
|
||||
getWatchedItems: vi.fn(),
|
||||
removeWatchedItem: vi.fn(),
|
||||
addWatchedItem: vi.fn(),
|
||||
getUserDietaryRestrictions: vi.fn(),
|
||||
setUserDietaryRestrictions: vi.fn(),
|
||||
getUserAppliances: vi.fn(),
|
||||
setUserAppliances: vi.fn(),
|
||||
},
|
||||
shoppingRepo: {
|
||||
getShoppingLists: vi.fn(),
|
||||
createShoppingList: vi.fn(),
|
||||
deleteShoppingList: vi.fn(),
|
||||
addShoppingListItem: vi.fn(),
|
||||
updateShoppingListItem: vi.fn(),
|
||||
removeShoppingListItem: vi.fn(),
|
||||
getShoppingListById: vi.fn(),
|
||||
},
|
||||
recipeRepo: {
|
||||
deleteRecipe: vi.fn(),
|
||||
updateRecipe: vi.fn(),
|
||||
},
|
||||
addressRepo: {
|
||||
getAddressById: vi.fn(),
|
||||
upsertAddress: vi.fn(),
|
||||
},
|
||||
notificationRepo: {
|
||||
getNotificationsForUser: vi.fn(),
|
||||
markAllNotificationsAsRead: vi.fn(),
|
||||
markNotificationAsRead: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock userService used by routes
|
||||
vi.mock('../../services/userService', () => ({
|
||||
userService: {
|
||||
updateUserAvatar: vi.fn(),
|
||||
updateUserPassword: vi.fn(),
|
||||
deleteUserAccount: vi.fn(),
|
||||
getUserAddress: vi.fn(),
|
||||
upsertUserAddress: vi.fn(),
|
||||
processTokenCleanupJob: vi.fn(),
|
||||
deleteUserAsAdmin: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../services/db/user.db', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../services/db/user.db')>();
|
||||
return {
|
||||
|
||||
@@ -88,7 +88,10 @@ export const resetMockIds = () => {
|
||||
* @returns A complete and type-safe User object.
|
||||
*/
|
||||
export const createMockUser = (overrides: Partial<User> = {}): User => {
|
||||
const userId = overrides.user_id ?? `user-${getNextId()}`;
|
||||
// Generate a deterministic, valid UUID-like string for mock user IDs.
|
||||
// This prevents database errors in integration tests where a UUID is expected.
|
||||
const userId =
|
||||
overrides.user_id ?? `00000000-0000-0000-0000-${String(getNextId()).padStart(12, '0')}`;
|
||||
|
||||
const defaultUser: User = {
|
||||
user_id: userId,
|
||||
@@ -175,6 +178,8 @@ export const createMockFlyer = (
|
||||
store_id: overrides.store_id ?? overrides.store?.store_id,
|
||||
});
|
||||
|
||||
const baseUrl = 'http://localhost:3001'; // A reasonable default for tests
|
||||
|
||||
// Determine the final file_name to generate dependent properties from.
|
||||
const fileName = overrides.file_name ?? `flyer-${flyerId}.jpg`;
|
||||
|
||||
@@ -192,8 +197,8 @@ export const createMockFlyer = (
|
||||
const defaultFlyer: Flyer = {
|
||||
flyer_id: flyerId,
|
||||
file_name: fileName,
|
||||
image_url: `/flyer-images/${fileName}`,
|
||||
icon_url: `/flyer-images/icons/icon-${fileName.replace(/\.[^/.]+$/, '.webp')}`,
|
||||
image_url: `${baseUrl}/flyer-images/${fileName}`,
|
||||
icon_url: `${baseUrl}/flyer-images/icons/icon-${fileName.replace(/\.[^/.]+$/, '.webp')}`,
|
||||
checksum: generateMockChecksum(fileName),
|
||||
store_id: store.store_id,
|
||||
valid_from: new Date().toISOString().split('T')[0],
|
||||
|
||||
0
src/tests/utils/userService.mock.ts
Normal file
0
src/tests/utils/userService.mock.ts
Normal file
@@ -44,10 +44,17 @@ const finalConfig = mergeConfig(
|
||||
// Otherwise, the inherited `exclude` rule will prevent any integration tests from running.
|
||||
// Setting it to an empty array removes all exclusion rules for this project.
|
||||
exclude: [],
|
||||
// Fix: Set environment variables to ensure generated URLs pass validation
|
||||
env: {
|
||||
NODE_ENV: 'test',
|
||||
BASE_URL: 'http://example.com', // Use a standard domain to pass strict URL validation
|
||||
PORT: '3000',
|
||||
},
|
||||
// This setup script starts the backend server before tests run.
|
||||
globalSetup: './src/tests/setup/integration-global-setup.ts',
|
||||
// The default timeout is 5000ms (5 seconds)
|
||||
testTimeout: 60000, // Increased timeout for server startup and API calls, especially AI services.
|
||||
hookTimeout: 60000,
|
||||
// "singleThread: true" is removed in modern Vitest.
|
||||
// Use fileParallelism: false to ensure test files run one by one to prevent port conflicts.
|
||||
fileParallelism: false,
|
||||
|
||||
Reference in New Issue
Block a user