React 测试库 + Jest:如何测试接收数字然后格式化的组件

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

我是测试组件的新手,我遇到了一个问题:我有一个组件接收一个数字作为 props,然后对其进行格式化:

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

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

我应该如何测试它?我无法通过 getByText("") 因为我还没有格式化的数字,我应该在我的测试中创建一个函数吗?

但是react-testing-library并没有测试逻辑,对吧?如果稍后我更改格式化方式怎么办?

是的,您可以使用 React 测试库非常轻松地测试业务逻辑:

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 测试库不关心组件的业务逻辑(实现细节),只关心组件在 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?

不需要这个,因为 React 测试库会自己执行该函数。

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

是的,它会执行组件内部的任何逻辑。

What if later I change the way I format it?

您将不得不更新相应的测试。