如何在Flutter控件测试中测试鼠标滚动事件? [英] How to test mouse scroll event on flutter widget tests?
问题描述
我将 PageView
小部件包装在 Listener
小部件内.如果 pointerSignal
是 PointerScrollEvent
,我会在其中检查 onPointerSignal
属性,以检测用户是否使用鼠标滚轮在小部件上滚动.然后,它不会产生怪异的行为,而是生成 animateToPage
,并将PageView的 physics
属性设置为 NeverScrollableScrollPhysics()
,因此不会干扰 animateToPage
过渡.
I've wrapped up PageView
widget inside a Listener
widget. There I check in onPointerSignal
property if pointerSignal
is PointerScrollEvent
to detect if the user used the mouse wheel to scroll on the widget. Then instead of doing the weird behaviour it produces I animateToPage
and I set physics
property of the PageView to NeverScrollableScrollPhysics()
so it does not interfere with animateToPage
transition.
那真的很酷!通过移动鼠标滚轮,可以平滑地从一页跳到另一页.
That is working really cool! It jumps from one page to another with a smooth animation by moving mouse wheel.
但是,通过小部件测试来测试行为时会很有趣.有人知道如何发出/发送 PointerScrollEvent
吗?我已经尝试了以下方法,但没有成功.
But fun comes when testing the behaviour through widget testing. Does someone know how to emit/dispatch a PointerScrollEvent
? I've tried the following without any success.
void main() {
testWidgets(
'when mouse wheel moved forward then next page is shown',
(WidgetTester tester) async {
await tester.pumpWidget(
Test(
child: PointerAwarePageView(
children: [
Text('1'),
Text('2'),
],
),
),
);
expect(find.text('1'), findsOneWidget);
tester.dispatchEvent(
PointerScrollEvent(scrollDelta: Offset(0.0, 1.0)),
HitTestResult(),
);
await tester.pump(Duration(seconds: 3));
expect(find.text('2'), findsOneWidget);
},
);
}
推荐答案
最后,我找到了一种方法.颤动测试启发了我: https://github.com/flutter/flutter/blob/master/packages/flutter/test/widgets/scrollable_test.dart#L316
Finally, I found a way to do it. This flutter test inspired me: https://github.com/flutter/flutter/blob/master/packages/flutter/test/widgets/scrollable_test.dart#L316
我们需要使用鼠标设备种类创建一个 TestPointer
并执行滚动.然后通过 WidgetTester
发送事件.
We need to create a TestPointer
with mouse device kind and perform scroll. Then send the event though WidgetTester
.
我将在这里写下我的工作结果测试:
I will write down here my working resulting test:
void main() {
testWidgets(
'when mouse wheel is scrolled then next page is shown',
(WidgetTester tester) async {
await tester.pumpWidget(
Test(
child: PointerAwarePageView(
children: [
Text('1'),
Text('2'),
],
),
),
);
expect(find.text('1'), findsOneWidget);
final Offset scrollEventLocation = tester.getCenter(find.byType(PointerAwarePageView));
final TestPointer testPointer = TestPointer(1, PointerDeviceKind.mouse);
testPointer.hover(scrollEventLocation);
final HitTestResult result = tester.hitTestOnBinding(scrollEventLocation);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 1.0)), result);
await tester.pumpAndSettle();
expect(find.text('2'), findsOneWidget);
},
);
}
这篇关于如何在Flutter控件测试中测试鼠标滚动事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!