React testing library + Jest: How to test a component that receives a number then format it

Viewed 535

I'm new at testing components and I'm facing a issue: I have a component that receives a number as props, and then format it:

const format = (number) => (number/ 100).toLocaleString("pt-BR", { style: "currency", currency: "BRL" });

<StatNumber>{format(number)}</StatNumber>

How I'm supposed to test it? I can't get by getByText("") because I don't have the formated number yet, should I create a funcion in my tests that do it?

But react-testing-library does not test logic, right? What if later I change the way I format it?

1 Answers

Yes, you can very easily test a business logic with React Testing library:

test('formatting number', async () => {
  render(<StatNumber number={5} />)

  expect(getByText('R$ 0,05')).toBeInTheDocument();
})

test('formatting big number', async () => {
  render(<StatNumber number={1999} />)

  expect(getByText('R$ 19,99')).toBeInTheDocument();
})

How I'm supposed to test it?

React Testing library does not care about the business logic of the component(implementation details), just what the component renders in DOM.

I can't get by getByText("") because I don't have the formated number yet, should I create a funcion in my tests that do it?

No need for this, as React Testing library will execute the function on its own.

But react-testing-library does not test logic, right?

Yes it does, it will execute any logic that is inside the component.

What if later I change the way I format it?

You will have to update the corresponding tests.

Related