2

我一直在尝试使用这个非常简单的测试文件来测试onScrolla 的事件:FlatList

测试文件:

// @ts-nocheck
import React from 'react';
import { fireEvent, render } from '@testing-library/react-native';
import { MyComponent } from '../../../src/modules/MyComponent';

describe('MyComponent', () => {
  it('should not call if IS_IOS is false', async () => {
    const { debug, getByTestId } = render(<MyComponent/>);

    fireEvent(getByTestId('alpha'), 'onScroll', {
      nativeEvent: {
        contentSize: { height: 600, width: 400 },
        contentOffset: { y: 150, x : 0 }
      }
    })

    debug();
  });
});

正在测试的组件:

import React from 'react';
import { FlatList, NativeScrollEvent, NativeSyntheticEvent, Text } from 'react-native';

interface Props {}

export const ChatRoomContainer = (props: Props) => {
  const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>): void => {};

  return (
    <FlatList
      inverted
      onScroll={ handleScroll }
      data={ [{}, {}, {}] }
      renderItem={ ({ item, index }: { item: any; index: number }) => {
        return <Text>dsafds</Text>;
      } }
      testID={ 'alpha' }
    />
  );
};

如您所见,我的方法中什至没有任何代码handleScroll,但我仍然收到此错误:

TypeError: Cannot read property 'height' of undefined

   8 |     const { debug, getByTestId } = render(<ChatRoomContainer>asdasd</ChatRoomContainer>);
   9 | 
> 10 |     fireEvent(getByTestId('alpha'), 'onScroll', {
     |     ^
  11 |       nativeEvent: {
  12 |         contentSize: { height: 600 },
  13 |         contentOffset: { y: 150 }

如何修复此错误并测试我的handleSCroll

在此先感谢您的时间!

4

1 回答 1

0

发生错误是因为事件数据缺少layoutMeasurement设置设备尺寸的字段。另外,与问题无关,我建议使用fireEvent.scroll触发滚动动作。

fireEvent.scroll(getByTestId('alpha'), {
    nativeEvent: {
        contentSize: { height: 600, width: 400 },
        contentOffset: { y: 150, x: 0 },
        layoutMeasurement: { height: 100, width: 100 } // Dimensions of the device
    }
})
于 2021-01-29T09:37:35.460 回答