简体   繁体   中英

Error in testing the properties of object using jest with react-testing-library

It's my first time to write tests. I'm writing tests for a ReactJS app wrote with hooks, and testing using Jest and react-testing-library .

I have trouble when I test object will render multiple times on its all properties.

Here's the functional component:

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;

Here's the test file:

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');
  });
});

What actually happens, is in every time the test expected 296-c-4f-89-18 which is the first property of the object, so how can i fix this?

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

I'm a bit confused by your code. In ItemDetails you are extracting the value code from item . But then in the test item hast the value { id: '296-c-4f-89-18', barcode: 'E-6' } .

Anyway, it looks like you want to check that the two parameters you pass are rendered. I would use getByText in this case:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM