我正在开发一个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);
});
但是我如何在测试小部件中模拟悬停(以检查容器是否为蓝色)?
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)));
,都遗憾地没有起作用。 - undefinedawait tester.sendEventToBinding(testPointer.scroll(const Offset(0, 0)));
是用于滚动的。我以为hover
函数是答案,但事实并非如此。请尝试查看这个 Flutter 测试的周围环境,找到答案:https://github.com/flutter/flutter/blob/master/packages/flutter/test/widgets/scrollable_test.dart#L316 - undefined