0

这是我第一次写测试。我正在为使用钩子编写的 ReactJS 应用程序编写测试,并使用Jestreact-testing-library 进行测试

当我测试对象将在其所有属性上多次呈现时,我遇到了麻烦。

这是功能组件:

const ItemDetails = ({ item }) => {
  const { code } = item;
  const { getBarcode } = useStationContext();

  return (
    <>
      <Button
        onClick={() => {
          getBarcode(code);
        }}
      >
        Print Barcode
      </Button>
      <List
        dataSource={formatData(item)}
        renderItem={({ title, value }) => (
          <List.Item>
            <List.Item.Meta
              description={
                <Wrapper>
                  <p>{upperCase(title)}</p>
                  <div data-testid="itmVal">{value}</div>
                </Wrapper>
              }
            />
          </List.Item>
        )}
      />
    </>
  );
};

export default ItemDetails;

这是测试文件:

beforeEach(cleanup);

describe('itemDetails()', () => {
  test('Return Details about item', () => {
    const { getByText, getByTestId, container, asFragment, debug } = render(
      <StationProvider>
        <ItemDetails
          item={{
            id: '296-c-4f-89-18',
            barcode: 'E-6',
          }}
        />
      </StationProvider>,
    );

    expect(getByTestId('itmVal')).toHaveTextContent(
      '296-c-4f-89-18',
    );
    expect(getByTestId('itmVal')).toHaveTextContent('E-6');
  });
});

实际发生的情况是,每次预期的测试296-c-4f-89-18都是对象的第一个属性,那么我该如何解决这个问题?

4

2 回答 2

1

我对你的代码有点困惑。在ItemDetails您从中提取值codeitem。但随后在测试item中有值{ id: '296-c-4f-89-18', barcode: 'E-6' }

无论如何,您似乎想检查您传递的两个参数是否已呈现。我会getByText在这种情况下使用:

const { getByText } = render(
  <StationProvider>
    <ItemDetails
      item={{
        id: '296-c-4f-89-18',
        barcode: 'E-6',
      }}
    />
  </StationProvider>,
);

expect(getByText('296-c-4f-89-18')).toBeInTheDocument()
expect(getByText('E-6')).toBeInTheDocument()
于 2019-02-15T09:38:53.253 回答
1

中的getBy函数react-testing-library将始终为您的查询返回第一个匹配项 - 如果要搜索所有匹配项,则需要使用getAllBy返回数组的函数。

于 2019-02-15T08:45:54.630 回答