DEV Community

André Peixoto
André Peixoto

Posted on

4

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs