Tests refactor
This commit is contained in:
parent
245520fb50
commit
99134d8556
165 changed files with 911 additions and 531 deletions
|
|
@ -0,0 +1,148 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { MealPlanRepository } from '../../../src/modules/meal-plans/meal-plans.repository.js';
|
||||
import { MealPlanStatus } from '@meshitrack/shared';
|
||||
|
||||
const { mockSave, MockMealPlanModel } = vi.hoisted(() => {
|
||||
const mockSave = vi.fn();
|
||||
function MockModel(this: { save: typeof mockSave }, data: unknown) {
|
||||
Object.assign(this, data);
|
||||
this.save = mockSave;
|
||||
}
|
||||
Object.assign(MockModel, {
|
||||
findOne: vi.fn(),
|
||||
find: vi.fn(),
|
||||
findOneAndUpdate: vi.fn(),
|
||||
findOneAndDelete: vi.fn(),
|
||||
});
|
||||
return { mockSave, MockMealPlanModel: MockModel };
|
||||
});
|
||||
|
||||
vi.mock('../../../src/schemas/meal-plan.schema.js', () => ({
|
||||
MealPlanModel: MockMealPlanModel,
|
||||
}));
|
||||
|
||||
const { MealPlanModel } = await import('../../../src/schemas/meal-plan.schema.js');
|
||||
|
||||
function makeChain(result: unknown = null) {
|
||||
return {
|
||||
sort: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: vi.fn().mockResolvedValue(result),
|
||||
};
|
||||
}
|
||||
|
||||
describe(MealPlanRepository.name, () => {
|
||||
let repo: MealPlanRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new MealPlanRepository();
|
||||
});
|
||||
|
||||
describe('findByHousehold', () => {
|
||||
it('applies householdId filter', async () => {
|
||||
const chain = makeChain([]);
|
||||
vi.mocked(MealPlanModel.find).mockReturnValue(chain as never);
|
||||
|
||||
await repo.findByHousehold('hh1', { limit: 20 });
|
||||
|
||||
expect(MealPlanModel.find).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ householdId: 'hh1' }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByWeek', () => {
|
||||
it('queries by householdId and weekStartDate', async () => {
|
||||
const mockPlan = { _id: 'mp1', weekStartDate: '2026-05-18' };
|
||||
vi.mocked(MealPlanModel.findOne).mockReturnValue(makeChain(mockPlan) as never);
|
||||
|
||||
const result = await repo.findByWeek('hh1', '2026-05-18');
|
||||
expect(MealPlanModel.findOne).toHaveBeenCalledWith({
|
||||
householdId: 'hh1',
|
||||
weekStartDate: '2026-05-18',
|
||||
});
|
||||
expect(result).toEqual(mockPlan);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('saves and returns new document', async () => {
|
||||
const plainDoc = { _id: 'new-id', weekStartDate: '2026-05-18' };
|
||||
mockSave.mockResolvedValue({ toObject: () => plainDoc });
|
||||
|
||||
const result = await repo.create({ weekStartDate: '2026-05-18' });
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result).toEqual(plainDoc);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateStatus', () => {
|
||||
it('updates status only', async () => {
|
||||
vi.mocked(MealPlanModel.findOneAndUpdate).mockReturnValue(makeChain({ _id: 'mp1' }) as never);
|
||||
|
||||
await repo.updateStatus('mp1', 'hh1', MealPlanStatus.ACTIVE);
|
||||
expect(MealPlanModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: 'mp1', householdId: 'hh1' },
|
||||
{ $set: { status: MealPlanStatus.ACTIVE } },
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('finds meal plan by id and householdId', async () => {
|
||||
const mockPlan = { _id: 'mp1', weekStartDate: '2026-05-18' };
|
||||
vi.mocked(MealPlanModel.findOne).mockReturnValue(makeChain(mockPlan) as never);
|
||||
|
||||
const result = await repo.findById('mp1', 'hh1');
|
||||
expect(MealPlanModel.findOne).toHaveBeenCalledWith({
|
||||
_id: 'mp1',
|
||||
householdId: 'hh1',
|
||||
});
|
||||
expect(result).toEqual(mockPlan);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates meal plan using findOneAndUpdate', async () => {
|
||||
vi.mocked(MealPlanModel.findOneAndUpdate).mockReturnValue(makeChain({ _id: 'mp1' }) as never);
|
||||
|
||||
await repo.update('mp1', 'hh1', { status: MealPlanStatus.ACTIVE });
|
||||
expect(MealPlanModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: 'mp1', householdId: 'hh1' },
|
||||
{ $set: { status: MealPlanStatus.ACTIVE } },
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('deletes meal plan using findOneAndDelete', async () => {
|
||||
vi.mocked(MealPlanModel.findOneAndDelete).mockReturnValue(makeChain({ _id: 'mp1' }) as never);
|
||||
|
||||
const result = await repo.delete('mp1', 'hh1');
|
||||
expect(MealPlanModel.findOneAndDelete).toHaveBeenCalledWith({
|
||||
_id: 'mp1',
|
||||
householdId: 'hh1',
|
||||
});
|
||||
expect(result).toEqual({ _id: 'mp1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByHousehold pagination cursor', () => {
|
||||
it('applies pagination filter when cursor is provided', async () => {
|
||||
const chain = makeChain([]);
|
||||
vi.mocked(MealPlanModel.find).mockReturnValue(chain as never);
|
||||
|
||||
const cursor = Buffer.from('some-mongo-id').toString('base64');
|
||||
await repo.findByHousehold('hh1', { limit: 20, cursor });
|
||||
|
||||
expect(MealPlanModel.find).toHaveBeenCalledWith({
|
||||
householdId: 'hh1',
|
||||
_id: { $gt: 'some-mongo-id' }
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
330
packages/api/tests/modules/meal-plans/meal-plans.routes.test.ts
Normal file
330
packages/api/tests/modules/meal-plans/meal-plans.routes.test.ts
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify from 'fastify';
|
||||
import { fastifyAwilixPlugin } from '@fastify/awilix';
|
||||
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
|
||||
import { MealPlanStatus } from '@meshitrack/shared';
|
||||
|
||||
vi.mock('jose', () => ({
|
||||
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
|
||||
jwtVerify: vi.fn().mockResolvedValue({
|
||||
payload: {
|
||||
sub: 'kc-1',
|
||||
email: 'test@example.com',
|
||||
preferred_username: 'testuser',
|
||||
realm_access: { roles: ['member'] },
|
||||
householdIds: ['hh1'],
|
||||
},
|
||||
protectedHeader: { alg: 'RS256' },
|
||||
key: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
const {
|
||||
mockFindByHousehold,
|
||||
mockFindById,
|
||||
mockFindByWeek,
|
||||
mockCreate,
|
||||
mockUpdate,
|
||||
mockUpdateStatus,
|
||||
mockDelete,
|
||||
} = vi.hoisted(() => ({
|
||||
mockFindByHousehold: vi.fn(),
|
||||
mockFindById: vi.fn(),
|
||||
mockFindByWeek: vi.fn(),
|
||||
mockCreate: vi.fn(),
|
||||
mockUpdate: vi.fn(),
|
||||
mockUpdateStatus: vi.fn(),
|
||||
mockDelete: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/meal-plans/meal-plans.repository.js', () => ({
|
||||
MealPlanRepository: class {
|
||||
findByHousehold = mockFindByHousehold;
|
||||
findById = mockFindById;
|
||||
findByWeek = mockFindByWeek;
|
||||
create = mockCreate;
|
||||
update = mockUpdate;
|
||||
updateStatus = mockUpdateStatus;
|
||||
delete = mockDelete;
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock prerequisite repositories to allow SuggestionEngine/Gap to resolve
|
||||
vi.mock('../../../src/modules/recipes/recipes.repository.js', () => ({
|
||||
RecipesRepository: class {
|
||||
findByHousehold = vi.fn().mockResolvedValue({ data: [] });
|
||||
findById = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/pantry/pantry.repository.js', () => ({
|
||||
PantryRepository: class {
|
||||
findActiveByHousehold = vi.fn().mockResolvedValue([]);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/nutrition-targets/nutrition-target.repository.js', () => ({
|
||||
NutritionTargetRepository: class {
|
||||
findByUser = vi.fn().mockResolvedValue(null);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/products/products.repository.js', () => ({
|
||||
ProductsRepository: class {
|
||||
findByIds = vi.fn().mockResolvedValue([]);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/users/users.repository.js', () => ({
|
||||
UsersRepository: class {
|
||||
findByKeycloakId = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||||
upsertFromToken = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
|
||||
},
|
||||
}));
|
||||
|
||||
import authPlugin from '../../../src/plugins/auth.plugin.js';
|
||||
import householdPlugin from '../../../src/plugins/household.plugin.js';
|
||||
import usersRoutes from '../../../src/modules/users/users.routes.js';
|
||||
import mealPlanRoutes from '../../../src/modules/meal-plans/meal-plans.routes.js';
|
||||
|
||||
const emptyNutrition = { calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, sugar: 0, sodium: 0, saturatedFat: 0, cholesterol: 0 };
|
||||
|
||||
function makePlan(overrides = {}) {
|
||||
return {
|
||||
_id: 'plan-1',
|
||||
householdId: 'hh1',
|
||||
weekStartDate: '2026-05-10',
|
||||
days: Array.from({ length: 7 }, (_, i) => ({
|
||||
date: `2026-05-${10 + i}`,
|
||||
meals: [],
|
||||
dailyNutritionTotal: emptyNutrition,
|
||||
})),
|
||||
status: MealPlanStatus.DRAFT,
|
||||
createdBy: 'kc-1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('meal-plan.routes', () => {
|
||||
let app: any;
|
||||
|
||||
async function buildTestApp() {
|
||||
const instance = Fastify({ logger: false });
|
||||
instance.setValidatorCompiler(validatorCompiler);
|
||||
instance.setSerializerCompiler(serializerCompiler);
|
||||
await instance.register(fastifyAwilixPlugin, {
|
||||
disposeOnClose: true,
|
||||
disposeOnResponse: true,
|
||||
strictBooleanEnforced: true,
|
||||
});
|
||||
await instance.register(authPlugin);
|
||||
await instance.register(householdPlugin);
|
||||
await instance.register(usersRoutes);
|
||||
await instance.register(mealPlanRoutes);
|
||||
await instance.ready();
|
||||
return instance;
|
||||
}
|
||||
|
||||
const authHeaders = { authorization: 'Bearer valid-token' };
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
app = await buildTestApp();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/meal-plans', () => {
|
||||
it('returns paginated results', async () => {
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [makePlan()],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/meal-plans',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0]._id).toBe('plan-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/meal-plans/week/:weekStartDate', () => {
|
||||
it('returns matched weekly plan', async () => {
|
||||
mockFindByWeek.mockResolvedValue(makePlan());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/meal-plans/week/2026-05-10',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()._id).toBe('plan-1');
|
||||
});
|
||||
|
||||
it('returns not-found message structure if missing', async () => {
|
||||
mockFindByWeek.mockResolvedValue(null);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/meal-plans/week/2026-05-10',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().message).toBe('No meal plan scheduled for this week');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/meal-plans', () => {
|
||||
it('creates a new plan', async () => {
|
||||
mockFindByWeek.mockResolvedValue(null);
|
||||
mockCreate.mockImplementation((data) => Promise.resolve({ ...data, _id: 'new-plan-id', createdAt: new Date(), updatedAt: new Date() }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/meal-plans',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
weekStartDate: '2026-05-10',
|
||||
days: Array.from({ length: 7 }, (_, i) => ({
|
||||
date: `2026-05-${10 + i}`,
|
||||
meals: [],
|
||||
dailyNutritionTotal: emptyNutrition,
|
||||
})),
|
||||
status: 'draft',
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body._id).toBe('new-plan-id');
|
||||
expect(body.status).toBe('draft');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/meal-plans/suggestions', () => {
|
||||
it('returns list of scored recipe recommendations', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/meal-plans/suggestions?limit=2',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/meal-plans/:id/gap', () => {
|
||||
it('returns missing elements report', async () => {
|
||||
mockFindById.mockResolvedValue(makePlan());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/meal-plans/plan-1/gap',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.mealPlanId).toBe('plan-1');
|
||||
expect(Array.isArray(body.missingItems)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/meal-plans/:id', () => {
|
||||
it('returns plan if found', async () => {
|
||||
const planWithMeal = makePlan({
|
||||
createdAt: new Date(),
|
||||
days: [{
|
||||
date: '2026-05-10',
|
||||
meals: [{
|
||||
id: '123e4567-e89b-42d3-a456-426614174000',
|
||||
type: 'dinner',
|
||||
recipeId: 'recipe-1',
|
||||
recipeName: 'Spaghetti',
|
||||
servings: 2,
|
||||
perServingNutrition: emptyNutrition,
|
||||
customName: 'My Pasta',
|
||||
customNutrition: emptyNutrition,
|
||||
notes: 'Very yummy',
|
||||
}],
|
||||
dailyNutritionTotal: emptyNutrition,
|
||||
}]
|
||||
});
|
||||
mockFindById.mockResolvedValue(planWithMeal);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/meal-plans/plan-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()._id).toBe('plan-1');
|
||||
expect(res.json().days[0].meals).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/households/:householdId/meal-plans/:id', () => {
|
||||
it('updates plan content and returns it', async () => {
|
||||
mockUpdate.mockResolvedValue(makePlan({ status: MealPlanStatus.ACTIVE }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/meal-plans/plan-1',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
status: MealPlanStatus.ACTIVE,
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().status).toBe(MealPlanStatus.ACTIVE);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/households/:householdId/meal-plans/:id/status', () => {
|
||||
it('updates plan status directly and returns it', async () => {
|
||||
mockUpdateStatus.mockResolvedValue(makePlan({ status: MealPlanStatus.ACTIVE }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/meal-plans/plan-1/status',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
status: MealPlanStatus.ACTIVE,
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().status).toBe(MealPlanStatus.ACTIVE);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/households/:householdId/meal-plans/:id', () => {
|
||||
it('deletes the plan and returns 204', async () => {
|
||||
mockDelete.mockResolvedValue(makePlan());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/households/hh1/meal-plans/plan-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(204);
|
||||
});
|
||||
});
|
||||
});
|
||||
261
packages/api/tests/modules/meal-plans/meal-plans.service.test.ts
Normal file
261
packages/api/tests/modules/meal-plans/meal-plans.service.test.ts
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { MealPlanService } from '../../../src/modules/meal-plans/meal-plans.service.js';
|
||||
import type { MealPlanRepository } from '../../../src/modules/meal-plans/meal-plans.repository.js';
|
||||
import { MealPlanStatus, MealType } from '@meshitrack/shared';
|
||||
import { BadRequestError, NotFoundError } from '../../../src/common/errors.js';
|
||||
|
||||
describe(MealPlanService.name, () => {
|
||||
let service: MealPlanService;
|
||||
let mockRepo: { [K in keyof MealPlanRepository]: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
mockRepo = {
|
||||
findByHousehold: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
findByWeek: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
updateStatus: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
} as never;
|
||||
|
||||
service = new MealPlanService({
|
||||
mealPlanRepository: mockRepo as unknown as MealPlanRepository,
|
||||
});
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const query = { limit: 10 };
|
||||
const mockResult = { data: [], pagination: { cursor: null, hasMore: false } };
|
||||
mockRepo.findByHousehold.mockResolvedValue(mockResult);
|
||||
|
||||
const result = await service.list('hh1', query);
|
||||
expect(mockRepo.findByHousehold).toHaveBeenCalledWith('hh1', query);
|
||||
expect(result).toEqual(mockResult);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getById', () => {
|
||||
it('returns plan if found', async () => {
|
||||
const mockPlan = { _id: 'p1' };
|
||||
mockRepo.findById.mockResolvedValue(mockPlan);
|
||||
|
||||
const result = await service.getById('p1', 'hh1');
|
||||
expect(mockRepo.findById).toHaveBeenCalledWith('p1', 'hh1');
|
||||
expect(result).toEqual(mockPlan);
|
||||
});
|
||||
|
||||
it('throws NotFoundError if not found', async () => {
|
||||
mockRepo.findById.mockResolvedValue(null);
|
||||
await expect(service.getById('p1', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
const mockPerServingNutrition = {
|
||||
calories: 100,
|
||||
protein: 10,
|
||||
carbs: 20,
|
||||
fat: 5,
|
||||
fiber: 2,
|
||||
sugar: 3,
|
||||
sodium: 100,
|
||||
saturatedFat: 1,
|
||||
cholesterol: 10,
|
||||
};
|
||||
|
||||
const emptyDays = Array.from({ length: 7 }, (_, i) => ({
|
||||
date: `2026-05-${10 + i}`,
|
||||
meals: [],
|
||||
dailyNutritionTotal: {
|
||||
calories: 0,
|
||||
protein: 0,
|
||||
carbs: 0,
|
||||
fat: 0,
|
||||
fiber: 0,
|
||||
sugar: 0,
|
||||
sodium: 0,
|
||||
saturatedFat: 0,
|
||||
cholesterol: 0,
|
||||
},
|
||||
}));
|
||||
|
||||
it('calculates day totals and delegates to repository', async () => {
|
||||
mockRepo.findByWeek.mockResolvedValue(null);
|
||||
mockRepo.create.mockImplementation((data) => Promise.resolve({ ...data, _id: 'new-id' }));
|
||||
|
||||
const daysWithMeal = [...emptyDays];
|
||||
daysWithMeal[0] = {
|
||||
date: '2026-05-10',
|
||||
meals: [
|
||||
{
|
||||
id: 'meal-uuid-1',
|
||||
type: MealType.BREAKFAST,
|
||||
recipeName: 'Eggs',
|
||||
servings: 2,
|
||||
perServingNutrition: mockPerServingNutrition,
|
||||
},
|
||||
],
|
||||
// Let's deliberately pass incorrect values to verify the service forces recalculation!
|
||||
dailyNutritionTotal: { calories: 999, protein: 99, carbs: 99, fat: 99 },
|
||||
};
|
||||
|
||||
const input = {
|
||||
weekStartDate: '2026-05-10',
|
||||
days: daysWithMeal,
|
||||
status: MealPlanStatus.DRAFT,
|
||||
};
|
||||
|
||||
const result = await service.create('hh1', 'user1', input);
|
||||
|
||||
expect(mockRepo.findByWeek).toHaveBeenCalledWith('hh1', '2026-05-10');
|
||||
expect(mockRepo.create).toHaveBeenCalled();
|
||||
|
||||
// Verify recalculation happened (perServing x 2 servings)
|
||||
expect(result.days[0].dailyNutritionTotal).toEqual({
|
||||
calories: 200,
|
||||
protein: 20,
|
||||
carbs: 40,
|
||||
fat: 10,
|
||||
fiber: 4,
|
||||
sugar: 6,
|
||||
sodium: 200,
|
||||
saturatedFat: 2,
|
||||
cholesterol: 20,
|
||||
});
|
||||
});
|
||||
|
||||
it('uses customNutrition over perServingNutrition if present', async () => {
|
||||
mockRepo.findByWeek.mockResolvedValue(null);
|
||||
mockRepo.create.mockImplementation((data) => Promise.resolve({ ...data, _id: 'new-id' }));
|
||||
|
||||
const daysWithCustom = [...emptyDays];
|
||||
daysWithCustom[1] = {
|
||||
date: '2026-05-11',
|
||||
meals: [
|
||||
{
|
||||
id: 'meal-uuid-2',
|
||||
type: MealType.LUNCH,
|
||||
recipeName: 'Custom Item',
|
||||
servings: 1,
|
||||
perServingNutrition: mockPerServingNutrition, // 100 calories
|
||||
customNutrition: {
|
||||
calories: 300,
|
||||
protein: 30,
|
||||
carbs: 5,
|
||||
fat: 15,
|
||||
},
|
||||
},
|
||||
],
|
||||
dailyNutritionTotal: { calories: 0, protein: 0, carbs: 0, fat: 0 },
|
||||
};
|
||||
|
||||
const input = {
|
||||
weekStartDate: '2026-05-10',
|
||||
days: daysWithCustom,
|
||||
status: MealPlanStatus.DRAFT,
|
||||
};
|
||||
|
||||
const result = await service.create('hh1', 'user1', input);
|
||||
expect(result.days[1].dailyNutritionTotal.calories).toBe(300);
|
||||
expect(result.days[1].dailyNutritionTotal.protein).toBe(30);
|
||||
});
|
||||
|
||||
it('throws BadRequestError if plan already exists for the week', async () => {
|
||||
mockRepo.findByWeek.mockResolvedValue({ _id: 'existing-id' });
|
||||
const input = {
|
||||
weekStartDate: '2026-05-10',
|
||||
days: emptyDays,
|
||||
status: MealPlanStatus.DRAFT,
|
||||
};
|
||||
|
||||
await expect(service.create('hh1', 'user1', input)).rejects.toThrow(BadRequestError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
const existingPlan = { _id: 'p1', householdId: 'hh1', status: MealPlanStatus.DRAFT };
|
||||
|
||||
beforeEach(() => {
|
||||
mockRepo.findById.mockResolvedValue(existingPlan);
|
||||
});
|
||||
|
||||
it('updates values and recalculates days if updated', async () => {
|
||||
mockRepo.update.mockImplementation((id, hh, data) => Promise.resolve({ ...existingPlan, ...data }));
|
||||
|
||||
const emptyDays = Array.from({ length: 7 }, (_, i) => ({
|
||||
date: `2026-05-${10 + i}`,
|
||||
meals: [],
|
||||
dailyNutritionTotal: {
|
||||
calories: 0,
|
||||
protein: 0,
|
||||
carbs: 0,
|
||||
fat: 0,
|
||||
fiber: 0,
|
||||
sugar: 0,
|
||||
sodium: 0,
|
||||
saturatedFat: 0,
|
||||
cholesterol: 0,
|
||||
},
|
||||
}));
|
||||
|
||||
const result = await service.update('p1', 'hh1', {
|
||||
status: MealPlanStatus.ACTIVE,
|
||||
days: emptyDays,
|
||||
});
|
||||
|
||||
expect(mockRepo.update).toHaveBeenCalledWith('p1', 'hh1', {
|
||||
status: MealPlanStatus.ACTIVE,
|
||||
days: emptyDays,
|
||||
});
|
||||
expect(result.status).toBe(MealPlanStatus.ACTIVE);
|
||||
});
|
||||
|
||||
it('supports updating shoppingListId', async () => {
|
||||
mockRepo.update.mockImplementation((id, hh, data) => Promise.resolve({ ...existingPlan, ...data }));
|
||||
const result = await service.update('p1', 'hh1', { shoppingListId: 'sl-1' });
|
||||
expect(mockRepo.update).toHaveBeenCalledWith('p1', 'hh1', { shoppingListId: 'sl-1' });
|
||||
expect((result as any).shoppingListId).toBe('sl-1');
|
||||
});
|
||||
|
||||
it('throws NotFoundError if update returns null', async () => {
|
||||
mockRepo.update.mockResolvedValue(null);
|
||||
await expect(service.update('p1', 'hh1', { status: MealPlanStatus.ACTIVE })).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateStatus', () => {
|
||||
it('delegates update status to repository', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'p1' });
|
||||
mockRepo.updateStatus.mockResolvedValue({ _id: 'p1', status: MealPlanStatus.ARCHIVED });
|
||||
|
||||
const result = await service.updateStatus('p1', 'hh1', MealPlanStatus.ARCHIVED);
|
||||
expect(mockRepo.updateStatus).toHaveBeenCalledWith('p1', 'hh1', MealPlanStatus.ARCHIVED);
|
||||
expect(result.status).toBe(MealPlanStatus.ARCHIVED);
|
||||
});
|
||||
|
||||
it('throws NotFoundError if updateStatus returns null', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'p1' });
|
||||
mockRepo.updateStatus.mockResolvedValue(null);
|
||||
await expect(service.updateStatus('p1', 'hh1', MealPlanStatus.ARCHIVED)).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('delegates deletion if found', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'p1' });
|
||||
mockRepo.delete.mockResolvedValue({ _id: 'p1' });
|
||||
|
||||
const result = await service.delete('p1', 'hh1');
|
||||
expect(mockRepo.delete).toHaveBeenCalledWith('p1', 'hh1');
|
||||
expect(result).toEqual({ _id: 'p1' });
|
||||
});
|
||||
|
||||
it('throws NotFoundError if delete returns null', async () => {
|
||||
mockRepo.findById.mockResolvedValue({ _id: 'p1' });
|
||||
mockRepo.delete.mockResolvedValue(null);
|
||||
await expect(service.delete('p1', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,234 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { ShoppingGapService } from '../../../src/modules/meal-plans/shopping-gap.service.js';
|
||||
import type { MealPlanRepository } from '../../../src/modules/meal-plans/meal-plans.repository.js';
|
||||
import type { RecipesRepository } from '../../../src/modules/recipes/recipes.repository.js';
|
||||
import type { PantryRepository } from '../../../src/modules/pantry/pantry.repository.js';
|
||||
import type { ProductsRepository } from '../../../src/modules/products/products.repository.js';
|
||||
import { NotFoundError } from '../../../src/common/errors.js';
|
||||
|
||||
describe(ShoppingGapService.name, () => {
|
||||
let service: ShoppingGapService;
|
||||
let mockMealRepo: { [K in keyof MealPlanRepository]: ReturnType<typeof vi.fn> };
|
||||
let mockRecipesRepo: { [K in keyof RecipesRepository]: ReturnType<typeof vi.fn> };
|
||||
let mockPantryRepo: { [K in keyof PantryRepository]: ReturnType<typeof vi.fn> };
|
||||
let mockProductsRepo: { [K in keyof ProductsRepository]: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
mockMealRepo = { findById: vi.fn() } as never;
|
||||
mockRecipesRepo = { findById: vi.fn() } as never;
|
||||
mockPantryRepo = { findActiveByHousehold: vi.fn() } as never;
|
||||
mockProductsRepo = { findByIds: vi.fn() } as never;
|
||||
|
||||
service = new ShoppingGapService({
|
||||
mealPlanRepository: mockMealRepo as unknown as MealPlanRepository,
|
||||
recipesRepository: mockRecipesRepo as unknown as RecipesRepository,
|
||||
pantryRepository: mockPantryRepo as unknown as PantryRepository,
|
||||
productsRepository: mockProductsRepo as unknown as ProductsRepository,
|
||||
});
|
||||
});
|
||||
|
||||
describe('calculateGap', () => {
|
||||
it('throws NotFoundError if plan is missing', async () => {
|
||||
mockMealRepo.findById.mockResolvedValue(null);
|
||||
await expect(service.calculateGap('hh1', 'p1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('correctly scales recipe ingredients and contrasts against pantry', async () => {
|
||||
// 1. Setup Meal Plan with 1 meal
|
||||
// Recipe A planned for 4 servings.
|
||||
mockMealRepo.findById.mockResolvedValue({
|
||||
_id: 'plan1',
|
||||
days: [
|
||||
{
|
||||
meals: [
|
||||
{ recipeId: 'recipe1', servings: 4 }
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
// 2. Recipe 1: serves 2, needs 100g of ProdA (total needed = 200g for 4 servings)
|
||||
mockRecipesRepo.findById.mockResolvedValue({
|
||||
_id: 'recipe1',
|
||||
servings: 2,
|
||||
ingredients: [
|
||||
{ productId: 'prodA', quantity: 100, unit: 'g', isOptional: false }
|
||||
]
|
||||
});
|
||||
|
||||
// 3. Products Info
|
||||
mockProductsRepo.findByIds.mockResolvedValue([
|
||||
{ _id: 'prodA', name: 'Flour', category: 'baking' }
|
||||
]);
|
||||
|
||||
// 4. Pantry only has 50g of ProdA. Missing amount should be 150g!
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([
|
||||
{ productId: 'prodA', quantity: 50 }
|
||||
]);
|
||||
|
||||
const result = await service.calculateGap('hh1', 'plan1');
|
||||
|
||||
expect(result.mealPlanId).toBe('plan1');
|
||||
expect(result.missingItems.length).toBe(1);
|
||||
|
||||
const gap = result.missingItems[0]!;
|
||||
expect(gap.productId).toBe('prodA');
|
||||
expect(gap.productName).toBe('Flour');
|
||||
expect(gap.requiredQuantity).toBe(200); // 100g * (4 planned / 2 base)
|
||||
expect(gap.pantryQuantity).toBe(50);
|
||||
expect(gap.missingQuantity).toBe(150);
|
||||
expect(gap.unit).toBe('g');
|
||||
});
|
||||
|
||||
it('does not include products that are fully stocked', async () => {
|
||||
mockMealRepo.findById.mockResolvedValue({
|
||||
_id: 'plan2',
|
||||
days: [
|
||||
{
|
||||
meals: [{ recipeId: 'recipe1', servings: 2 }]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
mockRecipesRepo.findById.mockResolvedValue({
|
||||
_id: 'recipe1',
|
||||
servings: 2,
|
||||
ingredients: [
|
||||
{ productId: 'prodB', quantity: 50, unit: 'g', isOptional: false }
|
||||
]
|
||||
});
|
||||
|
||||
mockProductsRepo.findByIds.mockResolvedValue([{ _id: 'prodB', name: 'Salt' }]);
|
||||
|
||||
// Pantry has 100g (more than enough)
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([{ productId: 'prodB', quantity: 100 }]);
|
||||
|
||||
const result = await service.calculateGap('hh1', 'plan2');
|
||||
expect(result.missingItems.length).toBe(0);
|
||||
});
|
||||
|
||||
it('aggregates duplicate ingredients and sorts by product name', async () => {
|
||||
mockMealRepo.findById.mockResolvedValue({
|
||||
_id: 'plan-multi',
|
||||
days: [
|
||||
{
|
||||
meals: [
|
||||
{ recipeId: 'recipeA', servings: 1 },
|
||||
{ recipeId: 'recipeB', servings: 1 },
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
mockRecipesRepo.findById.mockImplementation(async (id) => {
|
||||
if (id === 'recipeA') {
|
||||
return {
|
||||
_id: 'recipeA', servings: 1,
|
||||
ingredients: [{ productId: 'prod1', quantity: 10, isOptional: false }]
|
||||
};
|
||||
}
|
||||
return {
|
||||
_id: 'recipeB', servings: 1,
|
||||
ingredients: [
|
||||
{ productId: 'prod1', quantity: 20, isOptional: false },
|
||||
{ productId: 'prod2', quantity: 5, isOptional: false },
|
||||
]
|
||||
};
|
||||
});
|
||||
|
||||
mockProductsRepo.findByIds.mockResolvedValue([
|
||||
{ _id: 'prod1', name: 'Banana' },
|
||||
{ _id: 'prod2', name: 'Apple' },
|
||||
]);
|
||||
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([]);
|
||||
|
||||
const result = await service.calculateGap('hh1', 'plan-multi');
|
||||
|
||||
expect(result.missingItems).toHaveLength(2);
|
||||
expect(result.missingItems[0].productName).toBe('Apple');
|
||||
expect(result.missingItems[1].productName).toBe('Banana');
|
||||
expect(result.missingItems[1].requiredQuantity).toBe(30);
|
||||
});
|
||||
|
||||
it('covers fallback paths for missing list, recipe properties and pantry quantities', async () => {
|
||||
mockMealRepo.findById.mockResolvedValue({
|
||||
_id: 'plan-empty',
|
||||
});
|
||||
mockProductsRepo.findByIds.mockResolvedValue([]);
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([]);
|
||||
|
||||
let res = await service.calculateGap('hh1', 'plan-empty');
|
||||
expect(res.missingItems).toHaveLength(0);
|
||||
|
||||
mockMealRepo.findById.mockResolvedValue({
|
||||
_id: 'plan-missing',
|
||||
days: [
|
||||
{
|
||||
meals: [{ recipeId: 'recipeC', servings: 1 }]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
mockRecipesRepo.findById.mockResolvedValue({
|
||||
_id: 'recipeC',
|
||||
servings: 1,
|
||||
ingredients: [
|
||||
{ productId: 'prod3', quantity: 10, isOptional: false }
|
||||
]
|
||||
});
|
||||
|
||||
mockProductsRepo.findByIds.mockResolvedValue([
|
||||
{ _id: 'prod3' }
|
||||
]);
|
||||
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([
|
||||
{ productId: 'prod3' }
|
||||
]);
|
||||
|
||||
res = await service.calculateGap('hh1', 'plan-missing');
|
||||
expect(res.missingItems).toHaveLength(1);
|
||||
const itm = res.missingItems[0]!;
|
||||
expect(itm.unit).toBe('g');
|
||||
expect(itm.productName).toBe('Unknown Ingredient');
|
||||
expect(itm.category).toBe('other');
|
||||
expect(itm.pantryQuantity).toBe(0);
|
||||
});
|
||||
|
||||
it('skips optional ingredients, handles missing recipes and defaults servings to 1', async () => {
|
||||
mockMealRepo.findById.mockResolvedValue({
|
||||
_id: 'plan-edge',
|
||||
days: [
|
||||
{
|
||||
meals: [
|
||||
{ recipeId: 'recipeExist', servings: 2 },
|
||||
{ recipeId: 'recipeNotExist', servings: 1 },
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
mockRecipesRepo.findById.mockImplementation(async (id) => {
|
||||
if (id === 'recipeExist') {
|
||||
return {
|
||||
_id: 'recipeExist',
|
||||
servings: 0,
|
||||
ingredients: [
|
||||
{ productId: 'prodIng', quantity: 5, isOptional: false },
|
||||
{ productId: 'prodOptional', quantity: 10, isOptional: true },
|
||||
]
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
mockProductsRepo.findByIds.mockResolvedValue([{ _id: 'prodIng', name: 'Ingredient' }]);
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([]);
|
||||
|
||||
const result = await service.calculateGap('hh1', 'plan-edge');
|
||||
expect(result.missingItems).toHaveLength(1);
|
||||
expect(result.missingItems[0].productId).toBe('prodIng');
|
||||
expect(result.missingItems[0].requiredQuantity).toBe(10);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,272 @@
|
|||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { SuggestionEngineService } from '../../../src/modules/meal-plans/suggestion-engine.service.js';
|
||||
import type { RecipesRepository } from '../../../src/modules/recipes/recipes.repository.js';
|
||||
import type { PantryRepository } from '../../../src/modules/pantry/pantry.repository.js';
|
||||
import type { MealPlanRepository } from '../../../src/modules/meal-plans/meal-plans.repository.js';
|
||||
import type { NutritionTargetRepository } from '../../../src/modules/nutrition-targets/nutrition-target.repository.js';
|
||||
|
||||
describe(SuggestionEngineService.name, () => {
|
||||
let service: SuggestionEngineService;
|
||||
let mockRecipesRepo: { [K in keyof RecipesRepository]: ReturnType<typeof vi.fn> };
|
||||
let mockPantryRepo: { [K in keyof PantryRepository]: ReturnType<typeof vi.fn> };
|
||||
let mockMealPlanRepo: { [K in keyof MealPlanRepository]: ReturnType<typeof vi.fn> };
|
||||
let mockNutritionRepo: { [K in keyof NutritionTargetRepository]: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-05-20T00:00:00Z'));
|
||||
|
||||
mockRecipesRepo = {
|
||||
findByHousehold: vi.fn(),
|
||||
} as never;
|
||||
|
||||
mockPantryRepo = {
|
||||
findActiveByHousehold: vi.fn(),
|
||||
} as never;
|
||||
|
||||
mockMealPlanRepo = {
|
||||
findByHousehold: vi.fn(),
|
||||
} as never;
|
||||
|
||||
mockNutritionRepo = {
|
||||
findByUser: vi.fn(),
|
||||
} as never;
|
||||
|
||||
service = new SuggestionEngineService({
|
||||
recipesRepository: mockRecipesRepo as unknown as RecipesRepository,
|
||||
pantryRepository: mockPantryRepo as unknown as PantryRepository,
|
||||
mealPlanRepository: mockMealPlanRepo as unknown as MealPlanRepository,
|
||||
nutritionTargetRepository: mockNutritionRepo as unknown as NutritionTargetRepository,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('getSuggestions', () => {
|
||||
it('correctly ranks recipes based on inventory coverage and freshness', async () => {
|
||||
// 1. Set up recipes:
|
||||
// - Recipe A: Needs Product 1 (2 units) and Product 2 (1 unit)
|
||||
// - Recipe B: Needs Product 3 (1 unit)
|
||||
const recipeA = {
|
||||
_id: 'recipeA',
|
||||
name: 'Recipe A',
|
||||
ingredients: [
|
||||
{ productId: 'prod1', quantity: 2, isOptional: false },
|
||||
{ productId: 'prod2', quantity: 1, isOptional: false },
|
||||
],
|
||||
perServingNutrition: { calories: 400, protein: 30, carbs: 40, fat: 10 }, // balanced
|
||||
};
|
||||
|
||||
const recipeB = {
|
||||
_id: 'recipeB',
|
||||
name: 'Recipe B',
|
||||
ingredients: [
|
||||
{ productId: 'prod3', quantity: 1, isOptional: false },
|
||||
],
|
||||
perServingNutrition: { calories: 600, protein: 10, carbs: 100, fat: 15 }, // high carb
|
||||
};
|
||||
|
||||
mockRecipesRepo.findByHousehold.mockResolvedValue({
|
||||
data: [recipeA, recipeB],
|
||||
pagination: { hasMore: false },
|
||||
});
|
||||
|
||||
// 2. Set up Pantry inventory:
|
||||
// We have Product 1 in abundance (expiringSoon).
|
||||
// We have Product 2 (fresh).
|
||||
// Product 3 is NOT in pantry.
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([
|
||||
{
|
||||
productId: 'prod1',
|
||||
quantity: 10,
|
||||
freshnessEstimate: { daysRemaining: 2, urgency: 'expiringSoon' },
|
||||
},
|
||||
{
|
||||
productId: 'prod2',
|
||||
quantity: 5,
|
||||
freshnessEstimate: { daysRemaining: 15, urgency: 'fresh' },
|
||||
},
|
||||
]);
|
||||
|
||||
// 3. Set up standard nutrition target (Maintenance: 30p/40c/30f split)
|
||||
// Macro split match logic:
|
||||
// Recipe A: 400cals, 30g Protein(120cals=30%), 40g Carbs(160cals=40%), 10g Fat(90cals=22.5%) -> highly aligned!
|
||||
mockNutritionRepo.findByUser.mockResolvedValue({
|
||||
dailyCalories: 2000,
|
||||
proteinG: 150, // (150 * 4) = 600cals (30%)
|
||||
carbsG: 200, // (200 * 4) = 800cals (40%)
|
||||
fatG: 67, // (67 * 9) = 603cals (30%)
|
||||
});
|
||||
|
||||
// 4. Set up recent meal plans (empty history -> 100% Variety for all)
|
||||
mockMealPlanRepo.findByHousehold.mockResolvedValue({
|
||||
data: [],
|
||||
});
|
||||
|
||||
// Run suggestion fetch
|
||||
const suggestions = await service.getSuggestions('hh1', 'user1');
|
||||
|
||||
// Assertions:
|
||||
expect(suggestions.length).toBe(2);
|
||||
|
||||
// Recipe A should clearly rank #1 (100% Coverage, using urgent items, highly nutritious match)
|
||||
const top = suggestions[0]!;
|
||||
expect(top.recipeId).toBe('recipeA');
|
||||
expect(top.scores.coverage).toBe(1); // full coverage
|
||||
// Urgency: (expiringSoon[0.7] + fresh[0.1]) / 2 = 0.4
|
||||
expect(top.scores.urgency).toBeGreaterThan(0.3);
|
||||
expect(top.scores.variety).toBe(1); // never eaten
|
||||
|
||||
// Recipe B should have 0 coverage and thus lower totalScore
|
||||
const bottom = suggestions[1]!;
|
||||
expect(bottom.recipeId).toBe('recipeB');
|
||||
expect(bottom.scores.coverage).toBe(0);
|
||||
expect(bottom.totalScore).toBeLessThan(top.totalScore);
|
||||
});
|
||||
|
||||
it('penalizes recipes eaten recently (Variety score)', async () => {
|
||||
const recipeX = {
|
||||
_id: 'recipeX',
|
||||
name: 'Recipe X',
|
||||
ingredients: [],
|
||||
perServingNutrition: { calories: 100, protein: 5, carbs: 10, fat: 2 },
|
||||
};
|
||||
|
||||
mockRecipesRepo.findByHousehold.mockResolvedValue({ data: [recipeX] });
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([]);
|
||||
mockNutritionRepo.findByUser.mockResolvedValue(null);
|
||||
|
||||
// Fake history: Recipe X was eaten 7 days ago
|
||||
const date7DaysAgo = new Date();
|
||||
date7DaysAgo.setDate(date7DaysAgo.getDate() - 7);
|
||||
const dateStr = date7DaysAgo.toISOString().split('T')[0];
|
||||
|
||||
mockMealPlanRepo.findByHousehold.mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
days: [
|
||||
{
|
||||
date: dateStr,
|
||||
meals: [{ recipeId: 'recipeX' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const suggestions = await service.getSuggestions('hh1', 'user1');
|
||||
|
||||
// Variety calculation: 7 days ago / 14 days = 0.5
|
||||
expect(suggestions[0]!.scores.variety).toBeCloseTo(0.5, 1);
|
||||
});
|
||||
|
||||
it('triggers reasoning branches for partial coverage and urgent items', async () => {
|
||||
const recipeC = {
|
||||
_id: 'recipeC',
|
||||
name: 'Recipe C',
|
||||
ingredients: [
|
||||
{ productId: 'prod1', quantity: 10, isOptional: false },
|
||||
{ productId: 'prod2', quantity: 10, isOptional: false },
|
||||
],
|
||||
};
|
||||
|
||||
mockRecipesRepo.findByHousehold.mockResolvedValue({ data: [recipeC] });
|
||||
|
||||
// 1. Coverage: (10/10 + 5/10)/2 = 0.75 (hits >0.5)
|
||||
// 2. Urgency: both set to urgent = 1.0 (hits >0.7)
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([
|
||||
{ productId: 'prod1', quantity: 10, freshnessEstimate: { urgency: 'urgent' } },
|
||||
{ productId: 'prod2', quantity: 5, freshnessEstimate: { urgency: 'urgent' } },
|
||||
]);
|
||||
mockNutritionRepo.findByUser.mockResolvedValue(null);
|
||||
mockMealPlanRepo.findByHousehold.mockResolvedValue({ data: [] });
|
||||
|
||||
const suggestions = await service.getSuggestions('hh1', 'user1');
|
||||
expect(suggestions[0]!.scores.coverage).toBe(0.75);
|
||||
expect(suggestions[0]!.scores.urgency).toBe(1);
|
||||
expect(suggestions[0]!.reasoning).toContain('Uses several ingredients already stocked in your pantry.');
|
||||
expect(suggestions[0]!.reasoning).toContain('High priority: Saves expiring pantry items from going to waste!');
|
||||
});
|
||||
|
||||
it('triggers reasoning for moderately soon-to-expire items', async () => {
|
||||
const recipeD = {
|
||||
_id: 'recipeD',
|
||||
name: 'Recipe D',
|
||||
ingredients: [{ productId: 'prod1', quantity: 5, isOptional: false }],
|
||||
};
|
||||
|
||||
mockRecipesRepo.findByHousehold.mockResolvedValue({ data: [recipeD] });
|
||||
|
||||
// Urgency soon/expiringSoon has weight 0.7 (hits >0.4 branch)
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([
|
||||
{ productId: 'prod1', quantity: 5, freshnessEstimate: { urgency: 'expiringSoon' } },
|
||||
]);
|
||||
mockNutritionRepo.findByUser.mockResolvedValue(null);
|
||||
mockMealPlanRepo.findByHousehold.mockResolvedValue({ data: [] });
|
||||
|
||||
const suggestions = await service.getSuggestions('hh1', 'user1');
|
||||
expect(suggestions[0]!.scores.urgency).toBe(0.7);
|
||||
expect(suggestions[0]!.reasoning).toContain('Helps use up items that should be consumed soon.');
|
||||
});
|
||||
|
||||
it('aggregates duplicate pantry items and handles normal/default urgencies', async () => {
|
||||
const recipeE = {
|
||||
_id: 'recipeE',
|
||||
name: 'Recipe E',
|
||||
ingredients: [
|
||||
{ productId: 'prod1', quantity: 5, isOptional: false },
|
||||
],
|
||||
};
|
||||
|
||||
mockRecipesRepo.findByHousehold.mockResolvedValue({ data: [recipeE] });
|
||||
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([
|
||||
{ productId: 'prod1', quantity: 2, freshnessEstimate: { daysRemaining: 5, urgency: 'normal' } },
|
||||
{ productId: 'prod1', quantity: 3, freshnessEstimate: { daysRemaining: 10, urgency: 'unknown-type' } },
|
||||
]);
|
||||
mockNutritionRepo.findByUser.mockResolvedValue(null);
|
||||
mockMealPlanRepo.findByHousehold.mockResolvedValue({ data: [] });
|
||||
|
||||
const suggestions = await service.getSuggestions('hh1', 'user1');
|
||||
expect(suggestions[0]!.scores.coverage).toBe(1);
|
||||
expect(suggestions[0]!.scores.urgency).toBe(0.3);
|
||||
});
|
||||
|
||||
it('covers boundary logic for nameless recipes, custom meals, default targets and private weights', async () => {
|
||||
// 1. Nameless recipe and recipe without ingredients
|
||||
const rawRecipe = { _id: 'recipeMissingProps' };
|
||||
mockRecipesRepo.findByHousehold.mockResolvedValue({ data: [rawRecipe] });
|
||||
|
||||
// 2. Active target with partial/falsy info
|
||||
mockNutritionRepo.findByUser.mockResolvedValue({ dailyCalories: 0, proteinG: 0 });
|
||||
|
||||
// 3. Last eaten containing a custom meal without recipeId (should continue)
|
||||
mockMealPlanRepo.findByHousehold.mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
days: [
|
||||
{
|
||||
date: '2026-05-19',
|
||||
meals: [
|
||||
{ customName: 'Snack' }, // no recipeId!
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
mockPantryRepo.findActiveByHousehold.mockResolvedValue([]);
|
||||
|
||||
const suggestions = await service.getSuggestions('hh1', 'user1');
|
||||
|
||||
expect(suggestions).toHaveLength(1);
|
||||
|
||||
// 4. Direct call to getUrgencyWeight default branch
|
||||
const defaultWeight = (service as any).getUrgencyWeight('mystery-status');
|
||||
expect(defaultWeight).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue