在颤振测试中模拟悬停
Posted
技术标签:
【中文标题】在颤振测试中模拟悬停【英文标题】:Simulate hover in flutter test 【发布时间】:2021-05-21 00:04:43 【问题描述】:我正在开发一个 Flutter Web 项目,并且我有一个小部件想要编写测试。这个小部件使用MouseRegion
,当它被用户悬停或不悬停时,它会执行一些操作。
举个例子:
class MyWidget extends StatefulWidget
@override
_MyWidgetState createState() => _MyWidgetState();
class _MyWidgetState extends State<MyWidget>
bool isHovered = false;
@override
Widget build(BuildContext context)
return MouseRegion(
onExit: (_)
setState(()
isHovered = false;
);
,
onEnter: (_)
setState(()
isHovered = true;
);
,
child: Container(
color: isHovered ? Colors.blue : Colors.red,
height: 50,
width: 50,
)
);
我可以写一个小部件测试来测试我的容器是红色的:
testWidgets('MyWidget should be red by default', (WidgetTester tester) async
await tester.pumpWidget(
MyWidget(),
);
expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.red), findsOneWidget);
expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.blue), findsNothing);
);
但是如何在测试小部件中模拟悬停(以检查容器是否为蓝色)?
【问题讨论】:
相信这条评论能给你一个方向。 ***.com/a/64450668/10136855 感谢您的建议,我尝试添加final offset = tester.getCenter(find.byType(MyWidget)); final testPointer = TestPointer(1, PointerDeviceKind.mouse)..hover(offset); await tester.pumpAndSettle();
和 await tester.sendEventToBinding(testPointer.scroll(const Offset(0, 0)));
,但不幸的是没有成功
await tester.sendEventToBinding(testPointer.scroll(const Offset(0, 0)));
用于滚动。我认为悬停功能是答案,但不是。请尝试环顾这个颤振测试以找到答案github.com/flutter/flutter/blob/master/packages/flutter/test/…
【参考方案1】:
这就是我如何做到的
testWidgets('MyWidget should be red by default', (WidgetTester tester) async
await tester.pumpWidget(
MyWidget(),
);
expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.red), findsOneWidget);
expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.blue), findsNothing);
final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
addTearDown(gesture.removePointer);
await tester.pump();
await gesture.moveTo(tester.getCenter(find.byType(MyWidget)));
await tester.pumpAndSettle();
expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.red), findsNothing);
expect(find.byWidgetPredicate((Widget widget) => widget is Container && widget.color == Colors.blue), findsOneWidget);
);
【讨论】:
以上是关于在颤振测试中模拟悬停的主要内容,如果未能解决你的问题,请参考以下文章