Files
Shoppy/tests/ratingService.test.mjs
T
Frederik Spirgi 1d32aeaf29
Android Release Build / build-android (push) Successful in 13m35s
add better eco ratings
2026-10-26 11:42:28 +01:00

184 lines
8.0 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { calculateProductRating } from '../src/services/ratingService.js';
import { findAlternatives } from '../src/services/alternativesService.js';
import { mapOpenFoodFactsProduct } from '../src/services/productApi.js';
const preferences = { avoidAllergens: [], preferredDiet: 'none' };
const rate = (product, customPreferences = {}) => calculateProductRating(
{ id: 'test', ...product }, { ...preferences, ...customPreferences }
);
test('shows unknown when no category has reliable facts', () => {
const rating = rate({});
assert.equal(rating.overallScore, null);
assert.equal(rating.overallStatus, 'unknown');
});
test('missing budget and allergen data do not contribute neutral placeholder scores', () => {
const rating = rate({ nutrition: { nutriScore: 'A' } });
assert.equal(rating.categoryScores.budget.hasKnownFacts, false);
assert.equal(rating.categoryScores.allergies.hasKnownFacts, false);
assert.equal(rating.overallScore, 77);
assert.equal(rating.limitedByMissingData, true);
});
test('profile priorities actually change the category weighting', () => {
const item = { nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'E' } };
const nutritionFirst = rate(item, { nutritionPriority: 'high', sustainabilityPriority: 'low' });
const sustainabilityFirst = rate(item, { nutritionPriority: 'low', sustainabilityPriority: 'high' });
assert.ok(nutritionFirst.overallScore > sustainabilityFirst.overallScore);
});
test('ingredient text without animal terms is not treated as vegan proof', () => {
const rating = rate({ ingredients: ['Weizenmehl'] }, { preferredDiet: 'vegan' });
assert.equal(rating.categoryScores.ingredients.hasKnownFacts, false);
assert.equal(rating.overallStatus, 'unknown');
});
test('a confirmed avoided allergen still blocks the recommendation', () => {
const rating = rate({
allergens: ['Milch'], dataCompleteness: { allergens: true }, nutrition: { nutriScore: 'A' }
}, { avoidAllergens: ['Milch'] });
assert.equal(rating.overallScore, 0);
assert.equal(rating.overallStatus, 'critical');
assert.equal(rating.limitedByMissingData, false);
});
test('an OFF allergen list does not prove a different allergen is absent', () => {
const product = mapOpenFoodFactsProduct({
code: '123', allergens_tags: ['en:soybeans'], traces_tags: [], nutriscore_grade: 'a'
});
const rating = rate(product, { avoidAllergens: ['Milch'] });
assert.equal(rating.categoryScores.allergies.status, 'unknown');
assert.equal(rating.allergenReviewRequired, true);
assert.notEqual(rating.overallStatus, 'good');
});
test('possible traces of a selected allergen require review', () => {
const product = mapOpenFoodFactsProduct({
code: '124', allergens_tags: ['en:soybeans'], traces_tags: ['en:milk'], nutriscore_grade: 'a'
});
const rating = rate(product, { avoidAllergens: ['Milch'] });
assert.equal(rating.categoryScores.allergies.status, 'unknown');
assert.match(rating.allergenReviewMessage, /Spuren von Milch/);
assert.equal(rating.allergenReviewRequired, true);
});
test('a verified absence can contribute to the allergy score', () => {
const rating = rate({
allergens: ['Soja'], allergenTraces: [], dataCompleteness: { allergensVerified: true }
}, { avoidAllergens: ['Milch'] });
assert.equal(rating.categoryScores.allergies.score, 100);
assert.equal(rating.allergenReviewRequired, false);
});
test('empty additive tags without ingredients do not earn ingredient points', () => {
const product = mapOpenFoodFactsProduct({ code: '125', additives_tags: [] });
const rating = rate(product);
assert.equal(product.dataCompleteness.additives, false);
assert.equal(rating.categoryScores.ingredients.status, 'unknown');
});
test('selling countries do not stand in for ingredient origin', () => {
const product = mapOpenFoodFactsProduct({
code: '126', countries_tags: ['en:switzerland'], categories_tags: ['en:unknown-food']
});
const rating = rate(product);
assert.equal(product.sustainability.originCountry, undefined);
assert.deepEqual(product.sustainability.sellingCountries, ['en:switzerland']);
assert.equal(rating.categoryScores.sustainability.status, 'unknown');
const legacyCache = rate({
dataSource: 'cache', sustainability: { originCountry: 'Schweiz' }
});
assert.equal(legacyCache.categoryScores.sustainability.status, 'unknown');
});
test('stale cached facts cannot keep a green recommendation', () => {
const product = {
cacheStale: true,
nutrition: { nutriScore: 'A' },
ingredients: ['Hafer'],
ingredientAnalysis: { palmOil: false, additives: [] },
dataCompleteness: { additives: true },
sustainability: { ecoScore: 'A' }
};
assert.equal(rate({ ...product, cacheStale: false }).overallStatus, 'good');
const rating = rate(product);
assert.equal(rating.overallScore, 77);
assert.equal(rating.staleDataReviewRequired, true);
});
test('Nutri-Score nutrients are not penalized twice', () => {
const plain = rate({ nutrition: { nutriScore: 'C' } });
const flagged = rate({ nutrition: { nutriScore: 'C', nutrientLevels: { sugars: 'high' } } });
assert.equal(plain.categoryScores.nutrition.score, flagged.categoryScores.nutrition.score);
});
test('missing values for personal goals do not invent a penalty', () => {
const baseline = rate({ nutrition: { nutriScore: 'A' } });
const lowSugar = rate({ nutrition: { nutriScore: 'A' } }, { preferredDiet: 'lowSugar' });
const highProtein = rate({ nutrition: { nutriScore: 'A' } }, { preferredDiet: 'highProtein' });
assert.equal(lowSugar.categoryScores.nutrition.score, baseline.categoryScores.nutrition.score);
assert.equal(highProtein.categoryScores.nutrition.score, baseline.categoryScores.nutrition.score);
});
test('a critical additive in ingredient text counts without additive tags', () => {
const rating = rate({ ingredients: ['Farbstoff E171'] });
assert.equal(rating.categoryScores.ingredients.hasKnownFacts, true);
assert.ok(rating.categoryScores.ingredients.score <= 24);
});
test('flavoured water with sugar is not treated as plain water', () => {
const rating = rate({
name: 'Flavoured water',
categoryTags: ['en:waters', 'en:flavored-waters'],
nutrition: {
energyKjPer100g: 80,
sugarPer100g: 5,
saturatedFatPer100g: 0,
saltPer100g: 0,
proteinPer100g: 0,
fiberPer100g: 0,
fruitVegetableLegumePercent: 0,
hasNonNutritiveSweeteners: false
}
});
assert.notEqual(rating.categoryScores.nutrition.score, 98);
});
test('country names containing eu are not mistaken for the EU', () => {
const peru = rate({ sustainability: { originCountry: 'Peru' } });
const swiss = rate({ sustainability: { originCountry: 'Schweiz' } });
assert.equal(peru.categoryScores.sustainability.score, 35);
assert.equal(swiss.categoryScores.sustainability.score, 92);
});
test('Eco-Score is not counted again through its environmental indicators', () => {
const rating = rate({ sustainability: {
ecoScore: 'E', carbonFootprintKgCo2ePerKg: 0.1,
originCountry: 'Schweiz', packaging: 'Glas'
} });
assert.equal(rating.categoryScores.sustainability.score, 15);
});
test('alternatives exclude products whose allergens need review', async () => {
const source = {
id: 'source', barcode: '1', name: 'Original', category: 'Snacks', categoryTags: ['en:snacks'],
allergens: ['Milch'], dataCompleteness: { allergens: true }
};
const unknown = {
id: 'unknown', barcode: '2', name: 'Unklar', category: 'Snacks', categoryTags: ['en:snacks'],
allergens: [], dataCompleteness: { allergens: false }, nutrition: { nutriScore: 'A' }
};
const verified = {
id: 'verified', barcode: '3', name: 'Bestätigt', category: 'Snacks', categoryTags: ['en:snacks'],
allergens: ['Soja'], dataCompleteness: { allergens: true, allergensVerified: true }, nutrition: { nutriScore: 'A' }
};
const alternatives = await findAlternatives(source, {
...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true
}, { unknown, verified });
assert.deepEqual(alternatives.map((item) => item.product.id), ['verified']);
});