flutter - 小部件测试以断言文本小部件样式
问题描述
我正在构建一个任务/待办事项小部件。任务小部件是使用 aListTile
和Checkbox
小部件实现的。
class _TaskListItemState extends State<TaskListItem> {
@override
Widget build(BuildContext context) {
return InkWell(
onTap: _goToTaskScreen,
child: ListTile(
leading: Checkbox(
value: widget.task.isComplete, onChanged: _toggleTaskComplete),
title: Text(
widget.task.title,
style: TextStyle(
decoration: widget.task.isComplete
? TextDecoration.lineThrough
: null,
color: widget.task.isComplete ? Colors.grey : null),
),
),
);
}
void _goToTaskScreen() {...}
void _toggleTaskComplete(bool? value) {...});
}
}
我正在尝试测试小部件,如果任务完成,那么小部件的文本样式装饰应该是删除线,否则正常。
testWidgets(
'if the isCompleted is true, then title text should be strikethrough',
(WidgetTester tester) async {
// Arrange
const testKey = ValueKey('my-key-1');
const testTitle = 'Demo title';
const testProjectID = 555;
final DateTime testDueDate = DateTime.now();
const testIsComplete = true;
final Task taskComplete = Task(
title: testTitle,
projectID: testProjectID,
dueDate: testDueDate,
isComplete: testIsComplete);
await tester.pumpWidget(MaterialApp(
home: Material(
child: TaskListItem(key: testKey, task: taskComplete),
),
));
final textFinder = find.byType(Text);
final textWidget = tester.firstWidget(textFinder);
expect(textWidget.style.decoration, TextDecoration.lineThrough);
});
运行时应用程序运行良好flutter run
。
但这会在运行时引发错误flutter test
:
est/widgets/task_list_item_test.dart:57:25:错误:没有为类 'Widget' 定义 getter 'style'。
- “小部件”来自“package:flutter/src/widgets/framework.dart”(“/C:/flutter/packages/flutter/lib/src/widgets/framework.dart”)。尝试将名称更正为现有 getter 的名称,或定义一个名为“style”的 getter 或字段。期望(textWidget.style.decoration,TextDecoration.lineThrough);^^^^^
我知道我遗漏了一些东西,因为我只学习了一个多星期的颤振。你能帮我如何执行小部件测试来断言文本小部件样式。谢谢!
解决方案
在我自己遇到这个问题并研究了在小部件上测试/断言样式的解决方案后Text
,我发现了find.byWidgetPredicate
实现这一目标的最有效方法。
对于您的情况,您可以byWidgetPredicate
像这样使用:
// Define your finder with specific conditions here:
final textWithStrikeThrough = find.byWidgetPredicate(
(widget) =>
widget is Text &&
widget.style.decoration == TextDecoration.lineThrough,
description: '`Text` widget with strike through',
);
// Now you can use this finder like other finders.
expect(
textWithStrikeThrough,
findsOneWidget,
);
推荐阅读
- reporting-services - Dynamics CRM 在线报告:高级查找视图过滤
- ios - 如何找到 UITableViewCell 的 ViewController?
- java - 为什么循环迭代一次额外的时间?
- r - 用于数据分割的 R 编程
- sql - SQL:选择对应于不同列的最常出现的值
- firebase - angularfire2 会将时间戳值转换为 js 日期吗?
- ios - 是否可以在显示的屏幕层次结构中的特定元素上显示 UIViewController 以符合 Google Admob 政策?
- sas - 如何在 SAS VA 7.4 Designer 中创建累积中值字段?
- amazon-s3 - Terraform S3 多个未知数量的生命周期规则
- excel - Excel Vba to Word:如何将页码写入文本框?