testing - Flutter测试时如何找到Widget的 `text`属性?

标签 testing text dart flutter

我有一段代码可以创建文本小部件表格,如下所示:

return Table(
  defaultColumnWidth: FixedColumnWidth(120.0),
  children: <TableRow>[
    TableRow(
      children: <Widget>[Text('toffee'), Text('potato')],
    ),
    TableRow(
      children: <Widget>[Text('cheese'), Text('pie')],
    ),
  ],
);

我想测试表中的第一项确实是“太妃糖”这个词。我设置我的测试并进入这部分:

var firstCell = find
      .descendant(
        of: find.byType(Table),
        matching: find.byType(Text),
      )
      .evaluate()
      .toList()[0].widget;

  expect(firstCell, 'toffee');

这绝对行不通,因为 firstCell 是 Widget 类型,它不等于 String toffee

我只看到一个 toString() 函数,像这样:

'Text("toffee", inherit: true, color: Color(0xff616161), size: 16.0,
 textAlign: left)'

如何提取 text 属性以获得单词 toffee

现在看来我所能做的就是检查 .toString().contains('toffee'),这并不理想。

最佳答案

Rémi 的示例不太有效 - 它可能在他回答时有效,但此时调用 whereType<Text>()将始终返回一个空的 Iterable因为evaluate()返回 Iterable<Element> , 不是 Iterable<Widget> .但是,您可以获得 Element通过调用 .widget 的 Widget在上面,所以下面的代码应该可以工作:

Text firstText = find
    .descendant(
      of: find.byType(Table),
      matching: find.byType(Text),
    )
    .evaluate()
    .first
    .widget;

expect(firstText.data, 'toffee');

OP 非常接近工作代码 - 只有 2 个小问题:

  • 通过使用 var而不是 Text , 变量的类型是 Widget
  • WidgetString 进行比较- 这永远不会返回 true - 目的是比较 Widget 的属性到 String - 如果是 Text , String它显示是通过调用.data获得的在 Text

编辑:

WidgetTester现在具有用于检索小部件的实用函数:widget(Finder) , widgetList(Finder) , firstWidget(Finder)allWidgets .因此,对于 OP 的用例,您将使用 firstWidget像这样:

Text firstText = tester.firstWidget(
    find.descendant(
      of: find.byType(Table),
      matching: find.byType(Text),
    ));

expect(firstText.data, 'toffee');

关于testing - Flutter测试时如何找到Widget的 `text`属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52304957/

相关文章:

python - 在 Python 中清除窗口中的图形

dart - Flutter 自定义范围 slider

android - 如何使用 Flutter 处理应用程序生命周期(在 Android 和 iOS 上)?

testing - 如何回滚、重置或删除 Ecto 测试数据库?

ruby-on-rails - 使用新测试在 Rails 中出现未初始化的常量错误

ruby-on-rails - 如何测试依赖于 Devise signed_in 的 Rails 5 助手? helper ,用 Minitest?

testing - 如何测试数值分析例程?

python:循环遍历txt文件并删除前几行字符串

python - 如何将具有各种长度元组的 python 列表中的数据写入文件?

flutter - 我可以将TabBar中的标签向左而不是中心对齐吗?