我正在做一个 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);
});
但是如何模拟在测试小部件中的悬停(以检查容器是否为蓝色)?
答案 0 :(得分:2)
这是我设法做到的
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);
});