Pet*_*nko 3 javascript react-native react-native-testing-library
我一直在尝试使用这个非常简单的测试文件来测试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();
});
});
Run Code Online (Sandbox Code Playgroud)
正在测试的组件:
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' }
/>
);
};
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我的方法中甚至没有任何代码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 }
Run Code Online (Sandbox Code Playgroud)
如何修复此错误并测试我的handleSCroll?
发生错误的原因是事件数据缺少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
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5620 次 |
| 最近记录: |