0

I have a function that changes food ingredient amount and adjusts the macronutrients accordingly.

For example - changing 100g of rice to 150g, would 1.5x its macronutrients.

Here is my test code:

const fakeIngredient = {
  product_name: 'test',
  number_of_servings: 100,
  serving_quantity: 1,
  nutrients: {
    'energy-kcal_serving': 100,
    carbohydrates_serving: 3.75,
    fat_serving: 1.25,
    protein_serving: 3.773
  },
  amount: 100,
  uid: 'test'
};
const fakeIngredientChanged = {
  product_name: 'test',
  number_of_servings: 140,
  serving_quantity: 1,
  nutrients: {
    'energy-kcal_serving': 140,
    carbohydrates_serving: 5.25,
    fat_serving: 1.75,
    protein_serving: 5.2822
  },
  amount: 140,
  uid: 'test'
};

describe('Home', () => {
  it('should change amount of ingredient', () => {
    const result = changeAmountOfIngredient(
      fakeIngredient.serving_quantity,
      140,
      fakeIngredient
    );
    expect(result).toStrictEqual(fakeIngredientChanged);
  });
});

My test fails, because of this:

    -     "protein_serving": 5.2822,
    +     "protein_serving": 5.2822000000000005,

I manually created these 2 variables and used calculator to let calculated ingredient match 140g.

It seems like calculator gets the same number as my function, however the rounding is messed up?

What can I do to test this calculation function accurately, am I doing something wrong?

Ripas55
  • 423
  • 1
  • 6
  • 20
  • Welcome to the world of binary floating point. – Pointy Nov 06 '22 at 18:45
  • Instead of a simple comparison for equality, subtract one value from the other and verify that the absolute value of the difference is less than `0.000001` (or whatever you want as the threshold). Decimal math in binary floating point results in those representation quirks. – Pointy Nov 06 '22 at 18:51
  • 1
    https://jestjs.io/docs/expect#tobeclosetonumber-numdigits? – jonrsharpe Nov 06 '22 at 19:02

0 Answers0