FlatList renderItem的Jest快照测试



我有一个名为FlatListShadow的Flatlist包装器,但对于这篇文章来说,Flatlist影子和Flatlist是一样的东西

我需要在FlatListShadow中测试renderItem函数,它看起来像这个

renderItem={({ item }) => (
<Device
title={item.deviceName}
platform={item.platform}
updatedAt={item.updatedAt}
status={item.status}
selectDevice={() => selectDevice(item.deviceId)}
isSelected={selectedDeviceIdList.includes(item.deviceId)}
/>
)}

不幸的是,在快照中,它只提供信息

renderItem={[Function]}

如果您使用enzyme,您可以像这样实现

// prepare a mock item to render the renderItem with
const mockItem = {
deviceName: 'mock device name',
platform: 'mock platform',
updatedAt: 123,
status: 'mock status',
deviceId: '1-2-3-4',
}
describe('YourComponent', () => {
let shallowWrapper
beforeAll(() => {
shallowWraper = shallow(<YourComponent />);
});
it('should match the snapshot', () => {
// will generate snapshot for your component
expect(shallowWrapper).toMatchSnapshot();
});
describe('.renderItem', () => {
let renderItemShallowWrapper;
beforeAll(() => {
// find the component whose property is rendered as renderItem={[Function]}
// if we presume it's imported as ComponentWithRenderItemProp
// find it and get it's renderItem property 
RenderItem = shallowWraper.find(ComponentWithRenderItemProp).prop('renderItem');
// and since it's a component render it as such
// with mockItem
renderItemShallowWrapper = shallow(<RenderItem item={mockItem} />);
});
it('should match the snapshot', () => {
// generate snapshot for the renderItem
expect(renderItemShallowWrapper).toMatchSnapshot();
});
});
});

如果您使用的是jest:

describe('EasyToUseSection', () => {
it.only('flatlist should return renderItem correctly', () => {
const itemData = {
name: 'Name',
desc: 'Description',
};
const { getByTestId } = renderComponent();
expect(getByTestId('flatlist')).toBeDefined();
const element = getByTestId('flatlist').props.renderItem(itemData);
expect(element.props.data).toStrictEqual(itemData);
expect(element.type).toBe(Device);
});
});

通过这种方式,可以检查发送的数据,也可以检查组件渲染类型

最新更新