首页 > 解决方案 > 小部件测试以断言文本小部件样式

问题描述

我正在构建一个任务/待办事项小部件。任务小部件是使用 aListTileCheckbox小部件实现的。

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);^^^^^

我知道我遗漏了一些东西,因为我只学习了一个多星期的颤振。你能帮我如何执行小部件测试来断言文本小部件样式。谢谢!

标签: flutterflutter-test

解决方案


在我自己遇到这个问题并研究了在小部件上测试/断言样式的解决方案后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,
);


推荐阅读