我正在为呈现 FlatList 的组件编写一些单元测试,我需要模拟一些操作,例如scrollTo和scrollToEnd。
有人知道我怎样才能达到这个目标吗?
我正在使用 Jest 和 Enzyme 进行测试。
import React form "react";
import { FlatList } from 'react-native';
import { mount } from 'enzyme';
describe("<FlatList/>", () => {
const callback = jest.fn();
it("how to simulate scroll?", () => {
const list = mount(<FlatList onEndReach={callback}/>);
//how to simulate scrool and reach the end of the list?
expect(callback).toHaveBeenCalled();
})
})
从已安装对象的实例调用scrollToEnd()不起作用。
const flatList = wrapper.find(FlatList);
flatList.first().instance().scrollToEnd();
Expected mock function to have been called, but it was not called.
在我的模拟中,我想在调用 Flatlist.scrollToEnd() 时调用回调函数。
既然你测试你的组件而不是
FlatList
本身,我相信你最好以某种抽象的方式思考:而不是像模拟滚动这样的低级事物,只需调用道具:
list.find(FlatList).prop('onEndReach')();
或使用
simulate()
语法糖:
list.find(FlatList).simulate('endReach');
对我来说,它不仅比模拟滚动更容易,而且更易于维护。
看看这个:
it('should scrollend call request', async () => {
const {findByText, getByTestId} = render(component);
const flatList = getByTestId('listsFlatList');
const eventData = {
nativeEvent: {
contentOffset: {
y: 500,
x: 0,
},
contentSize: {
// Dimensions of the scrollable content
height: 500,
width: 100,
},
layoutMeasurement: {
// Dimensions of the device
height: 100,
width: 100,
},
},
};
await waitFor(() => fireEvent.scroll(flatList, eventData));
waitFor(() => {
expect(findByText('something')).toBeVisible();
});
});