react-native-testing-library - 在 FlatList 中测试 onScroll 事件
问题描述
我一直在尝试使用这个非常简单的测试文件来测试onScroll
a 的事件: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
?
在此先感谢您的时间!
解决方案
发生错误是因为事件数据缺少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
}
})
推荐阅读
- java - 我正在尝试在 Android 项目中生成 .pdf 文件
- c# - 如何在 C# 中实现异步任务?最佳实践
- javascript - Javascript for of 循环附加 JQuery 仅附加到第一个元素
- reactjs - 如何让基于属性的 CSS 样式与 Material-UI 和 JSS 中的本地规则引用一起使用?
- sql - 在 Oracle SQL 表的单独列中显示计数条件的结果
- ansible - Ansible 检查 sha1sum
- javascript - 如何从 Discord 消息中获取图像 URL?
- node.js - npx 在 github 上运行旧版本的 gist
- apache-kafka - 用于具有不同列名的现有表的 Kafka JDBC 接收器连接器?
- c - C中的“ps aux”命令