FlatList renderItem 的 Jest 快照测试

Ada*_*atz 1 snapshot jestjs react-native react-native-flatlist

我有一个名为 FlatListShadow 的 Flatlist 包装器,但对于这篇文章,FlatListShadow 和 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)}
      />
    )}
Run Code Online (Sandbox Code Playgroud)

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

renderItem={[Function]}
Run Code Online (Sandbox Code Playgroud)

Ten*_*eff 5

如果您正在使用,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();
    });
  });
});
Run Code Online (Sandbox Code Playgroud)