import {dataSource, GreenlyDataSource} from "../../config/dataSource"; import {FoodProductService} from "./foodProduct.service"; import {CarbonEmissionFactor} from "../carbonEmissionFactor/carbonEmissionFactor.entity"; import {seedTestCarbonEmissionFactors} from "../seed-dev-data"; import {FoodProductIngredient} from "./foodProductIngredient.entity"; import {FoodProduct} from "./foodProduct.entity"; let foodProductService: FoodProductService; beforeAll(async () => { await dataSource.initialize(); foodProductService = new FoodProductService( dataSource.getRepository(FoodProduct), dataSource.getRepository(CarbonEmissionFactor), ); }); describe("FoodProduct.service", () => { it("should initialize a food product from DTO", async () => { const hamCheesePizza = await foodProductService.initialize({ name: "hamCheesePizza", ingredients: [ { name: "ham", quantity: 0.1, unit: "kg" }, { name: "cheese", quantity: 0.15, unit: "kg" }, { name: "tomato", quantity: 0.4, unit: "kg" }, { name: "flour", quantity: 0.7, unit: "kg" }, { name: "oliveOil", quantity: 0.3, unit: "kg" }, ], }); expect(hamCheesePizza.ingredients).toHaveLength(5); expect(hamCheesePizza.ingredients?.[0].carbonEmissionFactor?.name).toBe("ham"); expect(hamCheesePizza.ingredients?.[0].carbonEmissionFactor?.unit).toBe("kg"); for (const ingredient of (hamCheesePizza.ingredients as FoodProductIngredient[])) expect(ingredient.carbonEmissionFactor?.id).not.toBeUndefined(); }); it("should create a food product from DTO", async () => { const noFoodProducts = await foodProductService.findAll(); expect(noFoodProducts).toHaveLength(0); const hamCheesePizza = await foodProductService.create({ name: "hamCheesePizza", ingredients: [ { name: "ham", quantity: 0.1, unit: "kg" }, { name: "cheese", quantity: 0.15, unit: "kg" }, { name: "tomato", quantity: 0.4, unit: "kg" }, { name: "flour", quantity: 0.7, unit: "kg" }, { name: "oliveOil", quantity: 0.3, unit: "kg" }, ], }); const retrievedHamCheesePizza = await dataSource .getRepository(FoodProduct) .findOne({ where: { name: "hamCheesePizza" }, relations: { ingredients: { carbonEmissionFactor: true } } }); expect(retrievedHamCheesePizza?.name).toBe("hamCheesePizza"); expect(retrievedHamCheesePizza?.ingredients).toHaveLength(5); expect(retrievedHamCheesePizza?.ingredients?.[0].carbonEmissionFactor?.name).toBe("ham"); expect(retrievedHamCheesePizza?.ingredients?.[0].carbonEmissionFactor?.unit).toBe("kg"); for (const ingredient of (retrievedHamCheesePizza?.ingredients as FoodProductIngredient[])) expect(ingredient.carbonEmissionFactor?.id).not.toBeUndefined(); const allFoodProducts = await foodProductService.findAll(); expect(allFoodProducts).toHaveLength(1); }); }); beforeEach(async () => { await GreenlyDataSource.cleanDatabase(); await seedTestCarbonEmissionFactors(); }); afterAll(async () => { await dataSource.destroy(); });