Tests refactor
This commit is contained in:
parent
245520fb50
commit
99134d8556
165 changed files with 911 additions and 531 deletions
|
|
@ -0,0 +1,279 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import { NutritionCalculatorService } from '../../../src/modules/recipes/nutrition-calculator.service.js';
|
||||
import { NutritionWarning } from '@meshitrack/shared';
|
||||
|
||||
const service = new NutritionCalculatorService();
|
||||
|
||||
function makeProduct(
|
||||
overrides: Partial<{
|
||||
servingSize: number;
|
||||
servingUnit: string;
|
||||
nutrition: Record<string, number>;
|
||||
}> = {},
|
||||
) {
|
||||
return {
|
||||
servingSize: overrides.servingSize ?? 100,
|
||||
servingUnit: overrides.servingUnit ?? 'g',
|
||||
nutrition: {
|
||||
calories: 200,
|
||||
protein: 20,
|
||||
carbs: 10,
|
||||
fat: 8,
|
||||
...(overrides.nutrition ?? {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe(NutritionCalculatorService.name, () => {
|
||||
describe('calculateRecipeNutrition', () => {
|
||||
it('calculates total and per-serving nutrition from one ingredient', () => {
|
||||
const product = makeProduct(); // 200 kcal per 100g
|
||||
const productMap = new Map([['p1', product]]);
|
||||
|
||||
const result = service.calculateRecipeNutrition(
|
||||
[{ productId: 'p1', quantity: 200 }], // 200g = 2 servings worth
|
||||
productMap,
|
||||
2, // 2 servings
|
||||
);
|
||||
|
||||
expect(result.totalNutrition.calories).toBe(400);
|
||||
expect(result.perServingNutrition.calories).toBe(200);
|
||||
expect(result.totalNutrition.protein).toBe(40);
|
||||
expect(result.perServingNutrition.protein).toBe(20);
|
||||
});
|
||||
|
||||
it('sums contributions from multiple ingredients', () => {
|
||||
const p1 = makeProduct({ nutrition: { calories: 100, protein: 10, carbs: 5, fat: 4 } });
|
||||
const p2 = makeProduct({ nutrition: { calories: 200, protein: 20, carbs: 10, fat: 8 } });
|
||||
const productMap = new Map([
|
||||
['p1', p1],
|
||||
['p2', p2],
|
||||
]);
|
||||
|
||||
const result = service.calculateRecipeNutrition(
|
||||
[
|
||||
{ productId: 'p1', quantity: 100 }, // 1× serving
|
||||
{ productId: 'p2', quantity: 100 }, // 1× serving
|
||||
],
|
||||
productMap,
|
||||
1,
|
||||
);
|
||||
|
||||
expect(result.totalNutrition.calories).toBe(300);
|
||||
expect(result.perServingNutrition.calories).toBe(300);
|
||||
});
|
||||
|
||||
it('uses zero nutrition for unknown product', () => {
|
||||
const productMap = new Map<string, ReturnType<typeof makeProduct>>();
|
||||
|
||||
const result = service.calculateRecipeNutrition(
|
||||
[{ productId: 'missing', quantity: 100 }],
|
||||
productMap,
|
||||
1,
|
||||
);
|
||||
|
||||
expect(result.totalNutrition.calories).toBe(0);
|
||||
});
|
||||
|
||||
it('propagates optional nutrients (sodium, fiber, sugar)', () => {
|
||||
const product = makeProduct({
|
||||
nutrition: {
|
||||
calories: 100,
|
||||
protein: 5,
|
||||
carbs: 10,
|
||||
fat: 2,
|
||||
sodium: 800,
|
||||
fiber: 4,
|
||||
sugar: 12,
|
||||
},
|
||||
});
|
||||
const productMap = new Map([['p1', product]]);
|
||||
|
||||
const result = service.calculateRecipeNutrition(
|
||||
[{ productId: 'p1', quantity: 100 }],
|
||||
productMap,
|
||||
1,
|
||||
);
|
||||
|
||||
expect(result.totalNutrition.sodium).toBe(800);
|
||||
expect(result.totalNutrition.fiber).toBe(4);
|
||||
expect(result.totalNutrition.sugar).toBe(12);
|
||||
});
|
||||
|
||||
it('propagates saturatedFat and cholesterol across multiple ingredients', () => {
|
||||
const p1 = makeProduct({
|
||||
nutrition: {
|
||||
calories: 100,
|
||||
protein: 5,
|
||||
carbs: 10,
|
||||
fat: 3,
|
||||
saturatedFat: 1.5,
|
||||
cholesterol: 30,
|
||||
},
|
||||
});
|
||||
const p2 = makeProduct({
|
||||
nutrition: {
|
||||
calories: 150,
|
||||
protein: 8,
|
||||
carbs: 12,
|
||||
fat: 5,
|
||||
saturatedFat: 2.5,
|
||||
cholesterol: 50,
|
||||
},
|
||||
});
|
||||
const productMap = new Map([
|
||||
['p1', p1],
|
||||
['p2', p2],
|
||||
]);
|
||||
|
||||
const result = service.calculateRecipeNutrition(
|
||||
[
|
||||
{ productId: 'p1', quantity: 100 },
|
||||
{ productId: 'p2', quantity: 100 },
|
||||
],
|
||||
productMap,
|
||||
1,
|
||||
);
|
||||
|
||||
expect(result.totalNutrition.saturatedFat).toBe(4);
|
||||
expect(result.totalNutrition.cholesterol).toBe(80);
|
||||
});
|
||||
|
||||
it('handles product with zero servingSize', () => {
|
||||
const product = makeProduct({ servingSize: 0 });
|
||||
const productMap = new Map([['p1', product]]);
|
||||
|
||||
const result = service.calculateRecipeNutrition(
|
||||
[{ productId: 'p1', quantity: 100 }],
|
||||
productMap,
|
||||
1,
|
||||
);
|
||||
|
||||
// ratio = 0 when servingSize = 0
|
||||
expect(result.totalNutrition.calories).toBe(0);
|
||||
});
|
||||
|
||||
it('handles zero servings', () => {
|
||||
const product = makeProduct();
|
||||
const productMap = new Map([['p1', product]]);
|
||||
|
||||
const result = service.calculateRecipeNutrition(
|
||||
[{ productId: 'p1', quantity: 100 }],
|
||||
productMap,
|
||||
0,
|
||||
);
|
||||
|
||||
expect(result.perServingNutrition.calories).toBe(0);
|
||||
});
|
||||
|
||||
it('multiplies saturatedFat and cholesterol by ratio', () => {
|
||||
const product = makeProduct({
|
||||
nutrition: {
|
||||
calories: 100,
|
||||
protein: 5,
|
||||
carbs: 10,
|
||||
fat: 3,
|
||||
saturatedFat: 2,
|
||||
cholesterol: 40,
|
||||
},
|
||||
});
|
||||
const productMap = new Map([['p1', product]]);
|
||||
|
||||
const result = service.calculateRecipeNutrition(
|
||||
[{ productId: 'p1', quantity: 200 }], // 2x serving
|
||||
productMap,
|
||||
2,
|
||||
);
|
||||
|
||||
// 2x ratio, then divide by 2 servings = same as per serving
|
||||
expect(result.totalNutrition.saturatedFat).toBe(4);
|
||||
expect(result.totalNutrition.cholesterol).toBe(80);
|
||||
expect(result.perServingNutrition.saturatedFat).toBe(2);
|
||||
expect(result.perServingNutrition.cholesterol).toBe(40);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateWarnings', () => {
|
||||
it('flags HIGH_CALORIES when > 800 kcal/serving', () => {
|
||||
const warnings = service.generateWarnings({
|
||||
calories: 900,
|
||||
protein: 20,
|
||||
carbs: 50,
|
||||
fat: 30,
|
||||
});
|
||||
expect(warnings).toContain(NutritionWarning.HIGH_CALORIES);
|
||||
});
|
||||
|
||||
it('flags HIGH_SODIUM when > 1500 mg/serving', () => {
|
||||
const warnings = service.generateWarnings({
|
||||
calories: 400,
|
||||
protein: 15,
|
||||
carbs: 30,
|
||||
fat: 10,
|
||||
sodium: 1600,
|
||||
});
|
||||
expect(warnings).toContain(NutritionWarning.HIGH_SODIUM);
|
||||
});
|
||||
|
||||
it('flags LOW_PROTEIN when < 10 g/serving', () => {
|
||||
const warnings = service.generateWarnings({
|
||||
calories: 300,
|
||||
protein: 5,
|
||||
carbs: 40,
|
||||
fat: 10,
|
||||
});
|
||||
expect(warnings).toContain(NutritionWarning.LOW_PROTEIN);
|
||||
});
|
||||
|
||||
it('flags LOW_FIBER when fiber is present and < 3 g/serving', () => {
|
||||
const warnings = service.generateWarnings({
|
||||
calories: 300,
|
||||
protein: 15,
|
||||
carbs: 40,
|
||||
fat: 10,
|
||||
fiber: 1,
|
||||
});
|
||||
expect(warnings).toContain(NutritionWarning.LOW_FIBER);
|
||||
});
|
||||
|
||||
it('does not flag LOW_FIBER when fiber is absent', () => {
|
||||
const warnings = service.generateWarnings({
|
||||
calories: 300,
|
||||
protein: 15,
|
||||
carbs: 40,
|
||||
fat: 10,
|
||||
});
|
||||
expect(warnings).not.toContain(NutritionWarning.LOW_FIBER);
|
||||
});
|
||||
|
||||
it('returns no warnings for a healthy meal', () => {
|
||||
const warnings = service.generateWarnings({
|
||||
calories: 450,
|
||||
protein: 30,
|
||||
carbs: 40,
|
||||
fat: 12,
|
||||
sodium: 600,
|
||||
fiber: 8,
|
||||
sugar: 10,
|
||||
saturatedFat: 4,
|
||||
cholesterol: 80,
|
||||
});
|
||||
expect(warnings).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('can return multiple warnings', () => {
|
||||
const warnings = service.generateWarnings({
|
||||
calories: 900,
|
||||
protein: 5,
|
||||
carbs: 80,
|
||||
fat: 40,
|
||||
sodium: 2000,
|
||||
sugar: 30,
|
||||
saturatedFat: 20,
|
||||
cholesterol: 250,
|
||||
fiber: 1,
|
||||
});
|
||||
expect(warnings.length).toBeGreaterThan(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
217
packages/api/tests/modules/recipes/recipes.repository.test.ts
Normal file
217
packages/api/tests/modules/recipes/recipes.repository.test.ts
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { mockFind, mockFindOne, mockFindOneAndUpdate, mockSave } = vi.hoisted(() => ({
|
||||
mockFind: vi.fn(),
|
||||
mockFindOne: vi.fn(),
|
||||
mockFindOneAndUpdate: vi.fn(),
|
||||
mockSave: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/schemas/recipe.schema.js', () => {
|
||||
const chain = () => ({
|
||||
sort: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFind,
|
||||
});
|
||||
|
||||
const findOneChain = () => ({
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFindOne,
|
||||
});
|
||||
|
||||
const updateChain = () => ({
|
||||
exec: mockFindOneAndUpdate,
|
||||
});
|
||||
|
||||
class FakeModel {
|
||||
data: unknown;
|
||||
constructor(data: unknown) {
|
||||
this.data = data;
|
||||
}
|
||||
save() {
|
||||
mockSave(this.data);
|
||||
return Promise.resolve({ toObject: () => this.data });
|
||||
}
|
||||
static find = vi.fn(() => chain());
|
||||
static findOne = vi.fn(() => findOneChain());
|
||||
static findOneAndUpdate = vi.fn(() => updateChain());
|
||||
}
|
||||
|
||||
return { RecipeModel: FakeModel };
|
||||
});
|
||||
|
||||
import { RecipesRepository } from '../../../src/modules/recipes/recipes.repository.js';
|
||||
|
||||
describe(RecipesRepository.name, () => {
|
||||
let repo: RecipesRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new RecipesRepository();
|
||||
});
|
||||
|
||||
describe('findByHousehold', () => {
|
||||
it('returns paginated list without filters', async () => {
|
||||
const items = [{ _id: { toString: () => 'r1' }, name: 'Recipe 1' }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', { limit: 20 });
|
||||
expect(result.data).toHaveLength(1);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('returns hasMore when more items exist', async () => {
|
||||
const items = Array.from({ length: 3 }, (_, i) => ({
|
||||
_id: { toString: () => `r${i}` },
|
||||
name: `Recipe ${i}`,
|
||||
}));
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByHousehold('hh1', { limit: 2 });
|
||||
expect(result.data).toHaveLength(2);
|
||||
expect(result.pagination.hasMore).toBe(true);
|
||||
expect(result.pagination.cursor).toBeTruthy();
|
||||
});
|
||||
|
||||
it('applies text search filter', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { q: 'pasta', limit: 20 });
|
||||
// No error thrown means the $text filter was applied
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies cuisine filter', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { cuisine: 'Italian', limit: 20 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies isFavorite filter', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { isFavorite: true, limit: 20 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies maxCalories filter', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { maxCalories: 500, limit: 20 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies tags filter', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { tags: 'vegetarian,quick', limit: 20 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips empty tags', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { tags: ',', limit: 20 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies cursor for pagination', async () => {
|
||||
const cursor = Buffer.from('abc123').toString('base64');
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { cursor, limit: 20 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('returns recipe when found', async () => {
|
||||
const recipe = { _id: 'r1', householdId: 'hh1', name: 'Recipe' };
|
||||
mockFindOne.mockResolvedValue(recipe);
|
||||
const result = await repo.findById('r1', 'hh1');
|
||||
expect(result).toEqual(recipe);
|
||||
});
|
||||
|
||||
it('returns null when not found', async () => {
|
||||
mockFindOne.mockResolvedValue(null);
|
||||
const result = await repo.findById('missing', 'hh1');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByProductId', () => {
|
||||
it('returns recipes containing the product', async () => {
|
||||
const items = [{ _id: { toString: () => 'r1' }, name: 'Recipe' }];
|
||||
mockFind.mockResolvedValue(items);
|
||||
|
||||
const result = await repo.findByProductId('hh1', 'p1', { limit: 20 });
|
||||
expect(result.data).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('supports cursor pagination', async () => {
|
||||
const cursor = Buffer.from('r1').toString('base64');
|
||||
mockFind.mockResolvedValue([]);
|
||||
const result = await repo.findByProductId('hh1', 'p1', { cursor, limit: 20 });
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('defaults limit to 20', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
const result = await repo.findByProductId('hh1', 'p1', {});
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findAllByProductId', () => {
|
||||
it('returns all recipes with the product', async () => {
|
||||
const recipes = [{ _id: 'r1' }, { _id: 'r2' }];
|
||||
mockFind.mockResolvedValue(recipes);
|
||||
const result = await repo.findAllByProductId('hh1', 'p1');
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('saves and returns the recipe', async () => {
|
||||
const data = { name: 'New Recipe', servings: 2, steps: [], tags: [], isFavorite: false };
|
||||
const computed = {
|
||||
ingredients: [],
|
||||
totalNutrition: { calories: 0, protein: 0, carbs: 0, fat: 0 },
|
||||
perServingNutrition: { calories: 0, protein: 0, carbs: 0, fat: 0 },
|
||||
warnings: [],
|
||||
};
|
||||
|
||||
const result = await repo.create(data, computed, 'hh1', 'user-1');
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result).toMatchObject({ name: 'New Recipe' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates and returns the recipe', async () => {
|
||||
const updated = { _id: 'r1', name: 'Updated' };
|
||||
mockFindOneAndUpdate.mockResolvedValue(updated);
|
||||
const result = await repo.update('r1', 'hh1', { name: 'Updated' });
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
|
||||
it('applies computed fields when provided', async () => {
|
||||
mockFindOneAndUpdate.mockResolvedValue({ _id: 'r1' });
|
||||
await repo.update(
|
||||
'r1',
|
||||
'hh1',
|
||||
{},
|
||||
{
|
||||
totalNutrition: { calories: 100, protein: 10, carbs: 5, fat: 3 },
|
||||
perServingNutrition: { calories: 100, protein: 10, carbs: 5, fat: 3 },
|
||||
warnings: [],
|
||||
},
|
||||
);
|
||||
expect(mockFindOneAndUpdate).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('softDelete', () => {
|
||||
it('sets deletedAt and returns', async () => {
|
||||
const deleted = { _id: 'r1', deletedAt: new Date() };
|
||||
mockFindOneAndUpdate.mockResolvedValue(deleted);
|
||||
const result = await repo.softDelete('r1', 'hh1');
|
||||
expect(result).toEqual(deleted);
|
||||
});
|
||||
});
|
||||
});
|
||||
471
packages/api/tests/modules/recipes/recipes.routes.test.ts
Normal file
471
packages/api/tests/modules/recipes/recipes.routes.test.ts
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
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';
|
||||
|
||||
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,
|
||||
mockFindByProductId,
|
||||
mockFindAllByProductId,
|
||||
mockCreate,
|
||||
mockUpdate,
|
||||
mockSoftDelete,
|
||||
} = vi.hoisted(() => ({
|
||||
mockFindByHousehold: vi.fn(),
|
||||
mockFindById: vi.fn(),
|
||||
mockFindByProductId: vi.fn(),
|
||||
mockFindAllByProductId: vi.fn(),
|
||||
mockCreate: vi.fn(),
|
||||
mockUpdate: vi.fn(),
|
||||
mockSoftDelete: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockFindByIds } = vi.hoisted(() => ({
|
||||
mockFindByIds: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/recipes/recipes.repository.js', () => ({
|
||||
RecipesRepository: class {
|
||||
findByHousehold = mockFindByHousehold;
|
||||
findById = mockFindById;
|
||||
findByProductId = mockFindByProductId;
|
||||
findAllByProductId = mockFindAllByProductId;
|
||||
create = mockCreate;
|
||||
update = mockUpdate;
|
||||
softDelete = mockSoftDelete;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/modules/products/products.repository.js', () => ({
|
||||
ProductsRepository: class {
|
||||
findByIds = mockFindByIds;
|
||||
findById = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
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 recipesRoutes from '../../../src/modules/recipes/recipes.routes.js';
|
||||
|
||||
const nutrition = { calories: 200, protein: 20, carbs: 10, fat: 8 };
|
||||
|
||||
function makeProduct(id = 'p1') {
|
||||
return {
|
||||
_id: id,
|
||||
householdId: 'hh1',
|
||||
servingSize: 100,
|
||||
servingUnit: 'g',
|
||||
nutrition,
|
||||
};
|
||||
}
|
||||
|
||||
function makeRecipe(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
_id: 'recipe-1',
|
||||
householdId: 'hh1',
|
||||
name: 'Grilled Chicken',
|
||||
servings: 2,
|
||||
ingredients: [
|
||||
{
|
||||
productId: 'p1',
|
||||
productName: 'Chicken Breast',
|
||||
quantity: 200,
|
||||
unit: 'g',
|
||||
isOptional: false,
|
||||
nutritionContribution: nutrition,
|
||||
},
|
||||
],
|
||||
steps: [{ order: 1, instruction: 'Grill the chicken.' }],
|
||||
tags: [],
|
||||
isFavorite: false,
|
||||
totalNutrition: nutrition,
|
||||
perServingNutrition: nutrition,
|
||||
warnings: [],
|
||||
createdBy: 'kc-1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('recipes.routes', () => {
|
||||
let app: Awaited<ReturnType<typeof buildTestApp>>;
|
||||
|
||||
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(recipesRoutes);
|
||||
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/recipes', () => {
|
||||
it('returns paginated list', async () => {
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [makeRecipe()],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/recipes',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].name).toBe('Grilled Chicken');
|
||||
expect(body.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('returns empty list', async () => {
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/recipes',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/recipes/:id', () => {
|
||||
it('returns recipe when found', async () => {
|
||||
mockFindById.mockResolvedValue(makeRecipe());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/recipes/recipe-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Grilled Chicken');
|
||||
});
|
||||
|
||||
it('returns recipe with all optional fields', async () => {
|
||||
mockFindById.mockResolvedValue(
|
||||
makeRecipe({
|
||||
description: 'A delicious dish',
|
||||
prepTime: 10,
|
||||
cookTime: 20,
|
||||
totalTime: 30,
|
||||
cuisine: 'Italian',
|
||||
imageUrl: 'https://example.com/image.jpg',
|
||||
source: {
|
||||
type: 'url',
|
||||
url: 'https://example.com/recipe',
|
||||
importedAt: new Date('2024-01-01'),
|
||||
},
|
||||
ingredients: [
|
||||
{
|
||||
productId: 'p1',
|
||||
productName: 'Chicken Breast',
|
||||
quantity: 200,
|
||||
unit: 'g',
|
||||
originalQuantity: 7,
|
||||
originalUnit: 'oz',
|
||||
preparation: 'diced',
|
||||
isOptional: false,
|
||||
nutritionContribution: nutrition,
|
||||
},
|
||||
],
|
||||
steps: [{ order: 1, instruction: 'Prep.', duration: 5, tip: 'Use sharp knife.' }],
|
||||
}),
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/recipes/recipe-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.description).toBe('A delicious dish');
|
||||
expect(body.prepTime).toBe(10);
|
||||
expect(body.cookTime).toBe(20);
|
||||
expect(body.totalTime).toBe(30);
|
||||
expect(body.cuisine).toBe('Italian');
|
||||
expect(body.imageUrl).toBe('https://example.com/image.jpg');
|
||||
expect(body.source.type).toBe('url');
|
||||
expect(body.source.url).toBe('https://example.com/recipe');
|
||||
expect(body.source.importedAt).toBeDefined();
|
||||
expect(body.ingredients[0].originalQuantity).toBe(7);
|
||||
expect(body.ingredients[0].originalUnit).toBe('oz');
|
||||
expect(body.ingredients[0].preparation).toBe('diced');
|
||||
expect(body.steps[0].duration).toBe(5);
|
||||
expect(body.steps[0].tip).toBe('Use sharp knife.');
|
||||
});
|
||||
|
||||
it('returns recipe with source but no url or importedAt', async () => {
|
||||
mockFindById.mockResolvedValue(
|
||||
makeRecipe({
|
||||
source: { type: 'manual' },
|
||||
}),
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/recipes/recipe-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.source.type).toBe('manual');
|
||||
expect(body.source.url).toBeUndefined();
|
||||
expect(body.source.importedAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns recipe with source.importedAt as string', async () => {
|
||||
mockFindById.mockResolvedValue(
|
||||
makeRecipe({
|
||||
source: {
|
||||
type: 'url',
|
||||
url: 'https://example.com',
|
||||
importedAt: '2024-01-01T00:00:00.000Z',
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/recipes/recipe-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().source.importedAt).toBe('2024-01-01T00:00:00.000Z');
|
||||
});
|
||||
|
||||
it('returns 404 when not found', async () => {
|
||||
mockFindById.mockResolvedValue(null);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/recipes/missing',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/recipes', () => {
|
||||
it('creates a recipe with metric ingredients', async () => {
|
||||
mockFindByIds.mockResolvedValue([makeProduct()]);
|
||||
mockCreate.mockResolvedValue(makeRecipe());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/recipes',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Grilled Chicken',
|
||||
servings: 2,
|
||||
ingredients: [
|
||||
{
|
||||
productId: 'p1',
|
||||
productName: 'Chicken Breast',
|
||||
quantity: 200,
|
||||
unit: 'g',
|
||||
isOptional: false,
|
||||
},
|
||||
],
|
||||
steps: [{ order: 1, instruction: 'Grill the chicken.' }],
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json().name).toBe('Grilled Chicken');
|
||||
});
|
||||
|
||||
it('rejects missing name', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/recipes',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ servings: 2, ingredients: [], steps: [] }),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/households/:householdId/recipes/:id', () => {
|
||||
it('updates a recipe name', async () => {
|
||||
const updated = makeRecipe({ name: 'Updated Recipe' });
|
||||
mockFindById.mockResolvedValue(makeRecipe());
|
||||
mockUpdate.mockResolvedValue(updated);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/recipes/recipe-1',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Updated Recipe' }),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Updated Recipe');
|
||||
});
|
||||
|
||||
it('updates recipe with new ingredients and recalculates', async () => {
|
||||
const updated = makeRecipe({ name: 'Grilled Chicken' });
|
||||
mockFindById.mockResolvedValue(makeRecipe());
|
||||
mockFindByIds.mockResolvedValue([makeProduct()]);
|
||||
mockUpdate.mockResolvedValue(updated);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/recipes/recipe-1',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
ingredients: [
|
||||
{
|
||||
productId: 'p1',
|
||||
productName: 'Chicken Breast',
|
||||
quantity: 300,
|
||||
unit: 'g',
|
||||
isOptional: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/households/:householdId/recipes/:id', () => {
|
||||
it('soft-deletes a recipe', async () => {
|
||||
mockFindById.mockResolvedValue(makeRecipe());
|
||||
mockSoftDelete.mockResolvedValue(makeRecipe());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/households/hh1/recipes/recipe-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(204);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/recipes/:id/scale', () => {
|
||||
it('returns scaled recipe preview', async () => {
|
||||
mockFindById.mockResolvedValue(makeRecipe());
|
||||
mockFindByIds.mockResolvedValue([makeProduct()]);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/recipes/recipe-1/scale',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ targetServings: 4 }),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.servings).toBe(4);
|
||||
expect(body.ingredients[0].quantity).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/recipes/import-text', () => {
|
||||
it('returns available:false with NoOp provider', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/recipes/import-text',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ text: 'Some recipe text' }),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().available).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:householdId/recipes/import-url', () => {
|
||||
it('returns available:false with NoOp provider', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/recipes/import-url',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ url: 'https://example.com/recipe' }),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().available).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:householdId/recipes/by-product/:productId', () => {
|
||||
it('returns recipes using a product', async () => {
|
||||
mockFindByProductId.mockResolvedValue({
|
||||
data: [makeRecipe()],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/recipes/by-product/p1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.data).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
344
packages/api/tests/modules/recipes/recipes.service.test.ts
Normal file
344
packages/api/tests/modules/recipes/recipes.service.test.ts
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { RecipesService } from '../../../src/modules/recipes/recipes.service.js';
|
||||
import { NotFoundError, BadRequestError } from '../../../src/common/errors.js';
|
||||
|
||||
const makeProduct = (id: string, servingUnit = 'g', servingSize = 100) => ({
|
||||
_id: { toString: () => id },
|
||||
householdId: 'hh1',
|
||||
name: 'Test Product',
|
||||
servingSize,
|
||||
servingUnit,
|
||||
densityGPerMl: undefined as number | undefined,
|
||||
nutrition: { calories: 200, protein: 20, carbs: 10, fat: 8 },
|
||||
});
|
||||
|
||||
const makeRecipe = (id = 'recipe-1') => ({
|
||||
_id: { toString: () => id },
|
||||
householdId: 'hh1',
|
||||
name: 'Test Recipe',
|
||||
servings: 2,
|
||||
ingredients: [
|
||||
{
|
||||
productId: 'p1',
|
||||
productName: 'Chicken',
|
||||
quantity: 200,
|
||||
unit: 'g',
|
||||
isOptional: false,
|
||||
nutritionContribution: { calories: 400, protein: 40, carbs: 0, fat: 16 },
|
||||
},
|
||||
],
|
||||
steps: [],
|
||||
tags: [],
|
||||
isFavorite: false,
|
||||
totalNutrition: { calories: 400, protein: 40, carbs: 0, fat: 16 },
|
||||
perServingNutrition: { calories: 200, protein: 20, carbs: 0, fat: 8 },
|
||||
warnings: [],
|
||||
createdBy: 'user-1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
describe(RecipesService.name, () => {
|
||||
const mockRecipesRepo = {
|
||||
findByHousehold: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
findByProductId: vi.fn(),
|
||||
findAllByProductId: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
softDelete: vi.fn(),
|
||||
};
|
||||
|
||||
const mockProductsRepo = {
|
||||
findById: vi.fn(),
|
||||
findByIds: vi.fn(),
|
||||
};
|
||||
|
||||
const mockLlmProvider = {
|
||||
extractNutrition: vi.fn(),
|
||||
parseRecipe: vi.fn(),
|
||||
parseRecipeFromUrl: vi.fn(),
|
||||
parseReceipt: vi.fn(),
|
||||
suggestMealPlan: vi.fn(),
|
||||
parseNaturalLanguage: vi.fn(),
|
||||
};
|
||||
|
||||
let service: RecipesService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new RecipesService({
|
||||
recipesRepository: mockRecipesRepo as never,
|
||||
productsRepository: mockProductsRepo as never,
|
||||
llmProvider: mockLlmProvider as never,
|
||||
});
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const expected = { data: [], pagination: { cursor: null, hasMore: false } };
|
||||
mockRecipesRepo.findByHousehold.mockResolvedValue(expected);
|
||||
|
||||
const result = await service.list('hh1', { limit: 20 });
|
||||
expect(mockRecipesRepo.findByHousehold).toHaveBeenCalledWith('hh1', { limit: 20 });
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getById', () => {
|
||||
it('returns recipe when found', async () => {
|
||||
const recipe = makeRecipe();
|
||||
mockRecipesRepo.findById.mockResolvedValue(recipe);
|
||||
|
||||
const result = await service.getById('recipe-1', 'hh1');
|
||||
expect(result).toEqual(recipe);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when not found', async () => {
|
||||
mockRecipesRepo.findById.mockResolvedValue(null);
|
||||
await expect(service.getById('missing', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('normalizes metric ingredients and calculates nutrition', async () => {
|
||||
const product = makeProduct('p1');
|
||||
mockProductsRepo.findByIds.mockResolvedValue([product]);
|
||||
mockRecipesRepo.create.mockResolvedValue(makeRecipe());
|
||||
|
||||
await service.create(
|
||||
{
|
||||
name: 'Test',
|
||||
servings: 2,
|
||||
ingredients: [
|
||||
{
|
||||
productId: 'p1',
|
||||
productName: 'Chicken',
|
||||
quantity: 200,
|
||||
unit: 'g',
|
||||
isOptional: false,
|
||||
},
|
||||
],
|
||||
steps: [],
|
||||
tags: [],
|
||||
isFavorite: false,
|
||||
},
|
||||
'hh1',
|
||||
'user-1',
|
||||
);
|
||||
|
||||
const [_, computed] = mockRecipesRepo.create.mock.calls[0]!;
|
||||
expect(computed.totalNutrition.calories).toBe(400); // 200g = 2× of 100g serving (200 kcal each)
|
||||
expect(computed.perServingNutrition.calories).toBe(200);
|
||||
});
|
||||
|
||||
it('throws BadRequestError for missing density on cup → g conversion', async () => {
|
||||
const product = makeProduct('p1', 'g'); // g product, no density
|
||||
mockProductsRepo.findByIds.mockResolvedValue([product]);
|
||||
|
||||
await expect(
|
||||
service.create(
|
||||
{
|
||||
name: 'Test',
|
||||
servings: 1,
|
||||
ingredients: [
|
||||
{
|
||||
productId: 'p1',
|
||||
productName: 'Sugar',
|
||||
quantity: 1,
|
||||
unit: 'cup',
|
||||
isOptional: false,
|
||||
},
|
||||
],
|
||||
steps: [],
|
||||
tags: [],
|
||||
isFavorite: false,
|
||||
},
|
||||
'hh1',
|
||||
'user-1',
|
||||
),
|
||||
).rejects.toThrow(BadRequestError);
|
||||
});
|
||||
|
||||
it('throws NotFoundError for unknown product', async () => {
|
||||
mockProductsRepo.findByIds.mockResolvedValue([]);
|
||||
|
||||
await expect(
|
||||
service.create(
|
||||
{
|
||||
name: 'Test',
|
||||
servings: 1,
|
||||
ingredients: [
|
||||
{
|
||||
productId: 'unknown',
|
||||
productName: 'X',
|
||||
quantity: 100,
|
||||
unit: 'g',
|
||||
isOptional: false,
|
||||
},
|
||||
],
|
||||
steps: [],
|
||||
tags: [],
|
||||
isFavorite: false,
|
||||
},
|
||||
'hh1',
|
||||
'user-1',
|
||||
),
|
||||
).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('soft-deletes recipe', async () => {
|
||||
const recipe = makeRecipe();
|
||||
mockRecipesRepo.findById.mockResolvedValue(recipe);
|
||||
mockRecipesRepo.softDelete.mockResolvedValue(recipe);
|
||||
|
||||
const result = await service.delete('recipe-1', 'hh1');
|
||||
expect(mockRecipesRepo.softDelete).toHaveBeenCalledWith('recipe-1', 'hh1');
|
||||
expect(result).toEqual(recipe);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when not found', async () => {
|
||||
mockRecipesRepo.findById.mockResolvedValue(null);
|
||||
await expect(service.delete('missing', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when softDelete returns null', async () => {
|
||||
mockRecipesRepo.findById.mockResolvedValue(makeRecipe());
|
||||
mockRecipesRepo.softDelete.mockResolvedValue(null);
|
||||
await expect(service.delete('recipe-1', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scale', () => {
|
||||
it('returns scaled ingredient quantities and recalculated nutrition', async () => {
|
||||
const recipe = makeRecipe();
|
||||
mockRecipesRepo.findById.mockResolvedValue(recipe);
|
||||
mockProductsRepo.findByIds.mockResolvedValue([makeProduct('p1')]);
|
||||
|
||||
const result = await service.scale('recipe-1', 'hh1', { targetServings: 4 });
|
||||
|
||||
expect(result.servings).toBe(4);
|
||||
// 200g × (4/2) = 400g
|
||||
expect(result.ingredients[0]!.quantity).toBe(400);
|
||||
expect(result.totalNutrition.calories).toBe(800);
|
||||
});
|
||||
});
|
||||
|
||||
describe('importFromText', () => {
|
||||
it('returns available:false when LLM returns null', async () => {
|
||||
mockLlmProvider.parseRecipe.mockResolvedValue(null);
|
||||
const result = await service.importFromText('some text', 'hh1');
|
||||
expect(result).toEqual({ available: false });
|
||||
});
|
||||
|
||||
it('returns draft when LLM returns a recipe', async () => {
|
||||
const draft = { name: 'Pasta', servings: 4, ingredients: [], steps: [] };
|
||||
mockLlmProvider.parseRecipe.mockResolvedValue(draft);
|
||||
const result = await service.importFromText('pasta recipe', 'hh1');
|
||||
expect(result).toEqual({ available: true, draft });
|
||||
});
|
||||
});
|
||||
|
||||
describe('importFromUrl', () => {
|
||||
it('returns available:false when LLM returns null', async () => {
|
||||
mockLlmProvider.parseRecipeFromUrl.mockResolvedValue(null);
|
||||
const result = await service.importFromUrl('https://example.com/recipe', 'hh1');
|
||||
expect(result).toEqual({ available: false });
|
||||
});
|
||||
|
||||
it('returns draft when LLM returns a recipe', async () => {
|
||||
const draft = { name: 'Soup', servings: 2, ingredients: [], steps: [] };
|
||||
mockLlmProvider.parseRecipeFromUrl.mockResolvedValue(draft);
|
||||
const result = await service.importFromUrl('https://example.com', 'hh1');
|
||||
expect(result).toEqual({ available: true, draft });
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates metadata without recalculating if no ingredients/servings changed', async () => {
|
||||
const recipe = makeRecipe();
|
||||
mockRecipesRepo.findById.mockResolvedValue(recipe);
|
||||
mockRecipesRepo.update.mockResolvedValue({ ...recipe, name: 'Renamed' });
|
||||
|
||||
const result = await service.update('recipe-1', 'hh1', { name: 'Renamed' });
|
||||
expect(result.name).toBe('Renamed');
|
||||
expect(mockProductsRepo.findByIds).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('recalculates nutrition when ingredients change', async () => {
|
||||
const recipe = makeRecipe();
|
||||
const product = makeProduct('p1');
|
||||
mockRecipesRepo.findById.mockResolvedValue(recipe);
|
||||
mockProductsRepo.findByIds.mockResolvedValue([product]);
|
||||
mockRecipesRepo.update.mockResolvedValue(recipe);
|
||||
|
||||
await service.update('recipe-1', 'hh1', {
|
||||
ingredients: [
|
||||
{
|
||||
productId: 'p1',
|
||||
productName: 'Chicken',
|
||||
quantity: 300,
|
||||
unit: 'g',
|
||||
isOptional: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(mockProductsRepo.findByIds).toHaveBeenCalled();
|
||||
expect(mockRecipesRepo.update).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('recalculates nutrition when only servings change', async () => {
|
||||
const recipe = makeRecipe();
|
||||
const product = makeProduct('p1');
|
||||
mockRecipesRepo.findById.mockResolvedValue(recipe);
|
||||
mockProductsRepo.findByIds.mockResolvedValue([product]);
|
||||
mockRecipesRepo.update.mockResolvedValue(recipe);
|
||||
|
||||
await service.update('recipe-1', 'hh1', { servings: 4 });
|
||||
|
||||
expect(mockProductsRepo.findByIds).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws NotFoundError when update returns null', async () => {
|
||||
mockRecipesRepo.findById.mockResolvedValue(makeRecipe());
|
||||
mockRecipesRepo.update.mockResolvedValue(null);
|
||||
|
||||
await expect(service.update('recipe-1', 'hh1', { name: 'X' })).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByProduct', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const expected = { data: [], pagination: { cursor: null, hasMore: false } };
|
||||
mockRecipesRepo.findByProductId.mockResolvedValue(expected);
|
||||
|
||||
const result = await service.findByProduct('hh1', 'p1', { limit: 20 });
|
||||
expect(mockRecipesRepo.findByProductId).toHaveBeenCalledWith('hh1', 'p1', { limit: 20 });
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recalculateForProduct', () => {
|
||||
it('recalculates all recipes containing the product', async () => {
|
||||
const recipe = makeRecipe();
|
||||
const product = makeProduct('p1');
|
||||
mockRecipesRepo.findAllByProductId.mockResolvedValue([recipe]);
|
||||
mockProductsRepo.findByIds.mockResolvedValue([product]);
|
||||
mockRecipesRepo.update.mockResolvedValue(recipe);
|
||||
|
||||
await service.recalculateForProduct('hh1', 'p1');
|
||||
|
||||
expect(mockRecipesRepo.findAllByProductId).toHaveBeenCalledWith('hh1', 'p1');
|
||||
expect(mockRecipesRepo.update).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does nothing when no recipes contain the product', async () => {
|
||||
mockRecipesRepo.findAllByProductId.mockResolvedValue([]);
|
||||
await service.recalculateForProduct('hh1', 'p1');
|
||||
expect(mockRecipesRepo.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import { toMetric } from '../../../src/modules/recipes/unit-conversion.service.js';
|
||||
|
||||
describe('toMetric', () => {
|
||||
describe('metric pass-through', () => {
|
||||
it('passes g through unchanged', () => {
|
||||
const r = toMetric(100, 'g', 'g');
|
||||
expect(r).toEqual({ ok: true, quantity: 100, unit: 'g' });
|
||||
});
|
||||
|
||||
it('passes ml through unchanged', () => {
|
||||
const r = toMetric(250, 'ml', 'ml');
|
||||
expect(r).toEqual({ ok: true, quantity: 250, unit: 'ml' });
|
||||
});
|
||||
|
||||
it('passes piece through unchanged', () => {
|
||||
const r = toMetric(2, 'piece', 'piece');
|
||||
expect(r).toEqual({ ok: true, quantity: 2, unit: 'piece' });
|
||||
});
|
||||
|
||||
it('passes slice through unchanged', () => {
|
||||
const r = toMetric(3, 'slice', 'slice');
|
||||
expect(r).toEqual({ ok: true, quantity: 3, unit: 'slice' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('mass conversions', () => {
|
||||
it('converts oz to g for a g-product', () => {
|
||||
const r = toMetric(1, 'oz', 'g');
|
||||
expect(r).toEqual({ ok: true, quantity: 28.35, unit: 'g' });
|
||||
});
|
||||
|
||||
it('converts lb to g for a g-product', () => {
|
||||
const r = toMetric(1, 'lb', 'g');
|
||||
expect(r).toEqual({ ok: true, quantity: 453.592, unit: 'g' });
|
||||
});
|
||||
|
||||
it('converts oz to ml using density for a ml-product', () => {
|
||||
// 1 oz = 28.3495 g; density 1.03 g/ml → 27.524... ml
|
||||
const r = toMetric(1, 'oz', 'ml', 1.03);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) {
|
||||
expect(r.unit).toBe('ml');
|
||||
expect(r.quantity).toBeCloseTo(27.524, 2);
|
||||
}
|
||||
});
|
||||
|
||||
it('returns MISSING_DENSITY for oz → ml when density absent', () => {
|
||||
const r = toMetric(1, 'oz', 'ml');
|
||||
expect(r).toMatchObject({ ok: false, code: 'MISSING_DENSITY' });
|
||||
});
|
||||
|
||||
it('returns INCOMPATIBLE_UNITS for oz → piece', () => {
|
||||
const r = toMetric(1, 'oz', 'piece');
|
||||
expect(r).toMatchObject({ ok: false, code: 'INCOMPATIBLE_UNITS' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('volume conversions', () => {
|
||||
it('converts tsp to ml for a ml-product', () => {
|
||||
const r = toMetric(1, 'tsp', 'ml');
|
||||
expect(r).toEqual({ ok: true, quantity: 4.929, unit: 'ml' });
|
||||
});
|
||||
|
||||
it('converts tbsp to ml for a ml-product', () => {
|
||||
const r = toMetric(1, 'tbsp', 'ml');
|
||||
expect(r).toEqual({ ok: true, quantity: 14.787, unit: 'ml' });
|
||||
});
|
||||
|
||||
it('converts fl_oz to ml for a ml-product', () => {
|
||||
const r = toMetric(1, 'fl_oz', 'ml');
|
||||
expect(r).toEqual({ ok: true, quantity: 29.574, unit: 'ml' });
|
||||
});
|
||||
|
||||
it('converts cup to ml for a ml-product', () => {
|
||||
const r = toMetric(1, 'cup', 'ml');
|
||||
expect(r).toEqual({ ok: true, quantity: 236.588, unit: 'ml' });
|
||||
});
|
||||
|
||||
it('converts cup to g using density for a g-product', () => {
|
||||
// 1 cup = 236.588 ml; density 1.05 g/ml → 248.417 g
|
||||
const r = toMetric(1, 'cup', 'g', 1.05);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) {
|
||||
expect(r.unit).toBe('g');
|
||||
expect(r.quantity).toBeCloseTo(248.417, 2);
|
||||
}
|
||||
});
|
||||
|
||||
it('returns MISSING_DENSITY for cup → g when density absent', () => {
|
||||
const r = toMetric(1, 'cup', 'g');
|
||||
expect(r).toMatchObject({ ok: false, code: 'MISSING_DENSITY' });
|
||||
});
|
||||
|
||||
it('returns INCOMPATIBLE_UNITS for cup → piece', () => {
|
||||
const r = toMetric(1, 'cup', 'piece');
|
||||
expect(r).toMatchObject({ ok: false, code: 'INCOMPATIBLE_UNITS' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('mass to ml cross-conversion', () => {
|
||||
it('converts oz to ml using density', () => {
|
||||
// 1 oz = 28.3495 g; density 0.9 g/ml → 28.3495 / 0.9 = 31.499... ml
|
||||
const r = toMetric(1, 'oz', 'ml', 0.9);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) {
|
||||
expect(r.unit).toBe('ml');
|
||||
expect(r.quantity).toBeCloseTo(31.499, 1);
|
||||
}
|
||||
});
|
||||
|
||||
it('returns MISSING_DENSITY for oz → ml when density absent', () => {
|
||||
const r = toMetric(1, 'oz', 'ml');
|
||||
expect(r).toMatchObject({ ok: false, code: 'MISSING_DENSITY' });
|
||||
});
|
||||
|
||||
it('returns INCOMPATIBLE_UNITS for oz → piece', () => {
|
||||
const r = toMetric(1, 'oz', 'piece');
|
||||
expect(r).toMatchObject({ ok: false, code: 'INCOMPATIBLE_UNITS' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('unknown unit', () => {
|
||||
it('returns INCOMPATIBLE_UNITS for unknown unit', () => {
|
||||
const r = toMetric(1, 'gallon' as never, 'g');
|
||||
expect(r).toMatchObject({ ok: false, code: 'INCOMPATIBLE_UNITS' });
|
||||
if (!r.ok) {
|
||||
expect(r.message).toContain('Unknown unit');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue