这是我第一次写测试。我正在为使用钩子编写的 ReactJS 应用程序编写测试,并使用Jest和react-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
都是对象的第一个属性,那么我该如何解决这个问题?