many fixes resulting from latest refactoring
Some checks failed
Deploy to Web Server flyer-crawler.projectium.com / deploy (push) Failing after 5m41s

This commit is contained in:
2025-12-09 00:05:54 -08:00
parent c1a032d5e6
commit 88fdb9886f
23 changed files with 95 additions and 143 deletions

View File

@@ -7,7 +7,7 @@ import * as apiClient from '../services/apiClient';
import { LeaderboardUser } from '../types';
// Mock the apiClient
vi.mock('../services/apiClient');
vi.mock('../services/apiClient'); // This was correct
const mockedApiClient = apiClient as Mocked<typeof apiClient>;
// Mock the logger

View File

@@ -9,7 +9,7 @@ import type { Flyer, MasterGroceryItem, FlyerItem, DealItem } from '../types';
const mockedApiClient = vi.mocked(apiClient);
// Mock the logger to prevent console noise
vi.mock('../services/logger', () => ({
vi.mock('../services/logger.client', () => ({
logger: {
error: vi.fn(),
},

View File

@@ -7,7 +7,7 @@ import * as apiClient from '../services/apiClient';
import { WatchedItemDeal } from '../types';
// Mock the apiClient. The component uses a local `fetchBestSalePrices` which calls `apiFetch`.
vi.mock('../services/apiClient');
vi.mock('../services/apiClient'); // This was correct
const mockedApiClient = apiClient as Mocked<typeof apiClient>;
// Mock the logger

View File

@@ -7,7 +7,7 @@ import * as apiClient from '../services/apiClient';
import { UserProfile, Achievement, UserAchievement } from '../types';
// Mock dependencies
vi.mock('../services/apiClient');
vi.mock('../services/apiClient'); // This was correct
vi.mock('../services/logger');
vi.mock('../services/notificationService');
vi.mock('../services/aiApiClient'); // Mock aiApiClient as it's used in the component

View File

@@ -17,10 +17,12 @@ vi.mock('../lib/queue', () => ({
}));
// Mock dependencies
vi.mock('../services/db/admin.db');
vi.mock('../services/db/flyer.db');
vi.mock('../services/db/recipe.db');
vi.mock('../services/db/user.db');
vi.mock('../services/db/index.db', () => ({
adminRepo: {},
flyerRepo: {},
recipeRepo: {},
userRepo: {},
}));
vi.mock('node:fs/promises');
vi.mock('../services/backgroundJobService', () => ({

View File

@@ -88,7 +88,7 @@ const createApp = (user?: UserProfile) => {
});
}
app.use('/api/admin', adminRouter);
app.use((err: Error, req: Request, res: Response ) => {
app.use((err: Error, req: Request, res: Response, _next: NextFunction) => {
res.status(500).json({ message: err.message || 'Internal Server Error' });
});
return app;

View File

@@ -48,34 +48,37 @@ vi.mock('bcrypt', async (importOriginal) => {
return { ...actual, compare: vi.fn() };
});
// Define a type for the custom passport callback to avoid `any`.
type PassportCallback = (error: Error | null, user: Express.User | false, info?: { message: string }) => void;
// Mock Passport middleware
vi.mock('./passport.routes', () => ({
default: {
authenticate: (strategy: string, options: Record<string, unknown>, callback: PassportCallback) => (req: Request, res: any) => {
// Logic to simulate passport authentication outcome based on test input
if (req.body.password === 'wrong_password') {
// Simulate incorrect credentials
return callback(null, false, { message: 'Incorrect email or password.' });
}
if (req.body.email === 'locked@test.com') {
// Simulate locked account
return callback(null, false, { message: 'Account is temporarily locked.' });
}
if (req.body.email === 'notfound@test.com') {
// Simulate user not found
return callback(null, false, { message: 'Login failed' });
}
vi.hoisted(() => {
// Define a type for the custom passport callback to avoid `any`.
type PassportCallback = (error: Error | null, user: Express.User | false, info?: { message: string }) => void;
// Default success case
const user = { user_id: 'user-123', email: req.body.email };
callback(null, user, undefined);
// Mock Passport middleware
vi.mock('./passport.routes', () => ({
default: {
authenticate: (strategy: string, options: Record<string, unknown>, callback: PassportCallback) => (req: Request, res: any) => {
// Logic to simulate passport authentication outcome based on test input
if (req.body.password === 'wrong_password') {
// Simulate incorrect credentials
return callback(null, false, { message: 'Incorrect email or password.' });
}
if (req.body.email === 'locked@test.com') {
// Simulate locked account
return callback(null, false, { message: 'Account is temporarily locked.' });
}
if (req.body.email === 'notfound@test.com') {
// Simulate user not found
return callback(null, false, { message: 'Login failed' });
}
// Default success case
const user = { user_id: 'user-123', email: req.body.email };
callback(null, user, undefined);
},
initialize: () => (req: any, res: any, next: any) => next(),
},
initialize: () => (req: any, res: any, next: any) => next(),
},
}));
}));
});
// Create a minimal Express app to host our router
const app = express();

View File

@@ -16,12 +16,10 @@ vi.mock('../services/db/index.db', () => ({
updateBudget: vi.fn(),
deleteBudget: vi.fn(),
getSpendingByCategory: vi.fn(),
}
}));
// Although not directly used by budget routes, the passport middleware is,
// and it depends on user.db. We must mock the functions it uses.
vi.mock('../services/db/user.db', () => ({
findUserProfileById: vi.fn(),
},
userRepo: {
findUserProfileById: vi.fn(),
},
}));
// Mock the logger to keep test output clean

View File

@@ -9,7 +9,7 @@ vi.unmock('./aiApiClient');
import * as aiApiClient from './aiApiClient';
// 1. Mock logger to keep output clean
vi.mock('./logger', () => ({
vi.mock('./logger.client', () => ({
logger: {
debug: vi.fn(),
info: vi.fn(),

View File

@@ -294,10 +294,8 @@ describe('API Client', () => {
it('deleteShoppingList should send a DELETE request to the correct URL', async () => {
const listId = 42;
let wasCalled = false;
server.use(
http.delete(`http://localhost/api/users/shopping-lists/${listId}`, () => {
wasCalled = true;
return new HttpResponse(null, { status: 204 });
})
);

View File

@@ -1,8 +1,8 @@
// src/services/db/connection.db.test.ts
import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
// Mock the logger
vi.mock('../logger', () => ({
// Mock the logger. This is a server-side DB test.
vi.mock('../logger.server', () => ({
logger: {
info: vi.fn(),
error: vi.fn(),

View File

@@ -8,8 +8,8 @@ vi.unmock('./gamification.db');
import { GamificationRepository } from './gamification.db';
import type { Achievement, UserAchievement, LeaderboardUser } from '../../types';
// Mock the logger
vi.mock('../logger', () => ({
// Mock the logger. This is a server-side DB test.
vi.mock('../logger.server', () => ({
logger: {
info: vi.fn(),
warn: vi.fn(),

View File

@@ -1,6 +1,6 @@
// src/services/db/personalization.db.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { mockPoolInstance } from '../../tests/setup/mock-db';
import { mockPoolInstance } from '../../tests/setup/tests-setup-unit';
import {
PersonalizationRepository} from './personalization.db';
import type { MasterGroceryItem, UserAppliance, DietaryRestriction, Appliance } from '../../types';
@@ -12,8 +12,8 @@ const mockQuery = mockPoolInstance.query;
const mockConnect = mockPoolInstance.connect;
import { ForeignKeyConstraintError } from './errors.db';
// Mock the logger to prevent console output during tests
vi.mock('../logger', () => ({
// Mock the logger to prevent console output during tests. This is a server-side DB test.
vi.mock('../logger.server', () => ({
logger: {
info: vi.fn(),
warn: vi.fn(),

View File

@@ -1,6 +1,6 @@
// src/services/db/recipe.db.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { mockPoolInstance } from '../../tests/setup/mock-db';
import { mockPoolInstance } from '../../tests/setup/tests-setup-unit';
import { RecipeRepository } from './recipe.db';
// Un-mock the module we are testing to ensure we use the real implementation.
@@ -10,8 +10,8 @@ const mockQuery = mockPoolInstance.query;
import type { Recipe, FavoriteRecipe, RecipeComment } from '../../types';
import { ForeignKeyConstraintError } from './errors.db';
// Mock the logger to prevent console output during tests
vi.mock('../logger', () => ({
// Mock the logger to prevent console output during tests. This is a server-side DB test.
vi.mock('../logger.server', () => ({
logger: {
info: vi.fn(),
warn: vi.fn(),

View File

@@ -1,6 +1,6 @@
// src/services/db/shopping.db.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { mockPoolInstance } from '../../tests/setup/mock-db';
import { mockPoolInstance } from '../../tests/setup/tests-setup-unit';
import { createMockShoppingList, createMockShoppingListItem } from '../../tests/utils/mockFactories';
// Un-mock the module we are testing to ensure we use the real implementation.
@@ -10,7 +10,7 @@ import { ShoppingRepository } from './shopping.db';
import { ForeignKeyConstraintError, UniqueConstraintError } from './errors.db';
// Mock the logger to prevent console output during tests
vi.mock('../logger', () => ({
vi.mock('../logger.server', () => ({
logger: {
info: vi.fn(),
warn: vi.fn(),

View File

@@ -30,7 +30,11 @@ import * as imageProcessor from '../utils/imageProcessor';
import { FlyerDataTransformer } from './flyerDataTransformer';
// Mock dependencies
vi.mock('./aiService.server');
vi.mock('./aiService.server', () => ({
aiService: {
extractCoreDataFromFlyerImage: vi.fn(),
},
}));
vi.mock('./db/flyer.db');
vi.mock('./db/index.db');
vi.mock('../utils/imageProcessor');
@@ -66,7 +70,7 @@ describe('FlyerProcessingService', () => {
// Instantiate the service with all its dependencies mocked
service = new FlyerProcessingService(
mockedAiService.aiService as any, // Cast because the real service is a class instance
mockedAiService.aiService,
mockedDb,
mockFs,
mocks.execAsync,

View File

@@ -3,35 +3,29 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
// --- Hoisted Mocks ---
const mocks = vi.hoisted(() => {
const mocks = {
// Create a mock EventEmitter to simulate IORedis connection events.
const mockRedisConnection = new EventEmitter();
// Add a mock 'ping' method required by other tests.
(mockRedisConnection as any).ping = vi.fn().mockResolvedValue('PONG');
mockRedisConnection: new EventEmitter(),
// Mock the Worker class from bullmq
const MockWorker = vi.fn(function (this: any, name: string) {
MockWorker: vi.fn(function (this: any, name: string) {
this.name = name;
this.on = vi.fn();
this.close = vi.fn().mockResolvedValue(undefined);
this.isRunning = vi.fn().mockReturnValue(true);
return this;
});
}),
// Mock the Queue class from bullmq
MockQueue: vi.fn(function (this: any, name: string) {
this.name = name;
this.add = vi.fn();
this.close = vi.fn().mockResolvedValue(undefined);
return this;
}),
};
// Add a mock 'ping' method required by other tests.
(mocks.mockRedisConnection as any).ping = vi.fn().mockResolvedValue('PONG');
return {
mockRedisConnection,
MockWorker,
// Mock the Queue class from bullmq
MockQueue: vi.fn(function (this: any, name: string) {
this.name = name;
this.add = vi.fn();
this.close = vi.fn().mockResolvedValue(undefined);
return this;
}),
};
});
// --- Mock Modules ---
// --- Mock Modules ---
vi.mock('bullmq', () => ({
Worker: mocks.MockWorker,
Queue: mocks.MockQueue,

View File

@@ -1,38 +0,0 @@
// src/tests/setup/mock-db.ts
import { vi } from 'vitest';
/**
* This file provides a centralized, stable mock for the 'pg' module.
* It exports the individual mock functions and instances so that any test file
* can import them directly for making assertions (e.g., `expect(mockQuery).toHaveBeenCalled()`).
*/
export const mockQuery = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 });
export const mockRelease = vi.fn();
export const mockConnect = vi.fn().mockResolvedValue({
query: mockQuery,
release: mockRelease,
});
export const mockPoolInstance = {
connect: mockConnect,
query: mockQuery,
end: vi.fn(),
on: vi.fn(),
totalCount: 10,
idleCount: 5,
waitingCount: 0,
};
// FIX: Use a standard function for the constructor here too.
// This ensures that if this mock factory is used, it supports `new MockPool()`.
export const MockPool = vi.fn(function() {
return mockPoolInstance;
});
// This is the actual mock factory function for vi.mock.
export const pgMockFactory = () => ({
Pool: MockPool,
default: { Pool: MockPool },
types: { setTypeParser: vi.fn() },
});

View File

@@ -1,12 +0,0 @@
// src/tests/setup/tests-setup-db.ts
import { Pool } from 'pg';
// This pool will automatically use the environment variables
// set by our global-setup.ts file when running tests.
export const testPool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: parseInt(process.env.DB_PORT || '5432', 10),
});

View File

@@ -98,9 +98,9 @@ vi.mock('pg', () => {
return {
// Named export must be the constructor
Pool: vi.fn(MockPool),
Pool: MockPool,
// Default export often contains Pool as a property
default: { Pool: vi.fn(MockPool) },
default: { Pool: MockPool },
types: { setTypeParser: vi.fn() },
};
});
@@ -235,7 +235,7 @@ vi.mock('@bull-board/express', () => ({
/**
* Mocks the logger.
*/
vi.mock('../../services/logger', () => ({
vi.mock('../../services/logger.client', () => ({
logger: {
info: vi.fn(),
warn: vi.fn(),

Some files were not shown because too many files have changed in this diff Show More