[英]flutter test not finding widget
我有这段代码可以测试按钮是否在屏幕上:
void main() {
testWidgets('Search for button', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: HomeView(),
));
final button = find.byType(BotaoRedirecionamentoInterno);
expect(button, findsWidgets);
});
}
按我的预期工作,但是当我尝试使用此代码在同一视图中搜索另一种类型的按钮时,它确实起作用了:
void main() {
testWidgets('Search for button', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: HomeView(),
));
final button = find.byType(BotaoRedirecionamentoExterno);
expect(button, findsWidgets);
});
}
我不明白为什么,因为它们恰好位于 HomeView 下方的一行:
Expanded(
child: GridView.count(
childAspectRatio: 6,
padding: EdgeInsets.only(left: screenWidth * .05, right: screenWidth * .05),
mainAxisSpacing: screenHeight * 0.02,
crossAxisCount: 1,
children: const [
BotaoRedirecionamentoInterno(texto: "aaa", rota: '/bbbb'),
BotaoRedirecionamentoExterno(texto: 'aaa', url: "bbb"),
BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
BotaoRedirecionamentoExterno(texto: "aaa", url: 'bbb'),
BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
],
),
)
这是错误信息:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
Expected: at least one matching node in the widget tree
Actual: _WidgetTypeFinder:<zero widgets with type "BotaoRedirecionamentoExterno" (ignoring
offstage widgets)>
我发现,如果我将 GridView 中的 position 更改为:
Expanded(
child: GridView.count(
childAspectRatio: 6,
padding: EdgeInsets.only(left: screenWidth * .05, right: screenWidth * .05),
mainAxisSpacing: screenHeight * 0.02,
crossAxisCount: 1,
children: const [
BotaoRedirecionamentoExterno(texto: 'aaa', url: "bbb"),
BotaoRedirecionamentoInterno(texto: "aaa", rota: '/bbbb'),
BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
BotaoRedirecionamentoExterno(texto: "aaa", url: 'bbb'),
BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
],
),
)
测试找到了 BotaoRedirecionamentoInterno 但找不到 BotaoRedirecionamentoExterno,所以我的猜测是只找到 GridView 中的第一个小部件。
任何人都可以帮我弄清楚发生了什么?
使用 dragUntilVisible 向右滚动 GridView,看下面一个它会滚动到BotaoRedirecionamentoExterno
小部件,你可以用任何Key
或Text
替换它..
await tester.dragUntilVisible(
find.byType(BotaoRedirecionamentoExterno), // what you want to find
find.byType(GridView), // widget you want to scroll
const Offset(-250, -0), // delta to move
);
该测试实际上可能按预期工作: Exanded
中的第二个子小部件在屏幕上不可见,因此无法找到。 find
方法只会返回已创建的 Widget,如果不可见, Gridview
不会创建所有的 Widget。 如果您交换订单,它确实显示的事实表明第一个Interno
小部件很大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.