我有一段代码可以创建文本小部件表格,如下所示:
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
Widget
与String
进行比较- 这永远不会返回 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/