Zeyad Etman
Zeyad Etman

Reputation: 2550

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?

Upvotes: 0

Views: 4734

Answers (2)

Gio Polvara
Gio Polvara

Reputation: 27018

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

Upvotes: 1

Joe Clay
Joe Clay

Reputation: 35817

The getBy functions in react-testing-library will always return the first matching item for your query - if you want to search for all matching items, you need to use the getAllBy functions, which return an array.

Upvotes: 1

Related Questions