DEV Community

André Peixoto
André Peixoto

Posted on

Validating String in Jest

Hi commiters!

Perhaps you have encountered a problem with validating strings in Jest.

test fail



For example, the test above validates that the function receives a value and returns a rounded value.

it('It should properly format a unit value with rounding.', () => {
    expect(formatCurrency(1234.56, true, false)).toEqual({
      measure: 'thousand',
      value: 'R$ 1.200,00',
    });
  });
Enter fullscreen mode Exit fullscreen mode

In this test, Jest returned an error, highlighting the differences between the expected and received values, but they are the same 🤯

- Expected  - 1
+ Received  + 1

  Object {
    "measure": "thousand",
-   "value": "R$ 1.200,00",
+   "value": "R$ 1.200,00",
Enter fullscreen mode Exit fullscreen mode

The solution is to add \xa0. The problem is not with your string, but how Jest compares string values 🤡

The corrected code is shown above.

it('It should properly format a unit value with rounding.', () => {
    expect(formatCurrency(1234.56, true, false)).toEqual({
      measure: 'thousand',
      value: 'R$\xa01.200,00', // remove space and add \xa0
    });
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)