我正在尝试为具有多个 TextFormFields 的屏幕编写集成测试。对于每个测试,我只是:
- 点击文本字段
- 输入一些文字
- 检查文本字段中是否存在文本。
使用 Flutter 驱动程序,以下内容适用于每个 TextFormField:
final myTextField = find.byValueKey('TextField');
test('Enter text into text field', () async {
await driver.tap(myTextField);
await driver.enterText('Hello world');
await driver.waitFor(find.text('Hello world'));
});
但是,对于屏幕外的任何 TextFormFields(即不可见/在视口之外),测试会因超时错误而失败。
我尝试添加scrollIntoView()
测试以告诉 Flutter Driver 滚动,直到该字段位于视口中。下面是一个例子:
final myTextField = find.byValueKey('TextField');
test('Enter text into text field', () async {
await driver.scrollIntoView(myTextField); // Added
await driver.tap(myTextField);
await driver.enterText('Hello world');
await driver.waitFor(find.text('Hello world'));
});
但是,测试继续失败并出现超时错误:
FlutterDriver: tap message is taking a long time to complete...
00:39 +0 -1: My screen: Enter text into text field [E]
TimeoutException after 0:00:30.000000: Test timed out after 30 seconds.
如何测试视口之外的 TextFormFields?
更新:我发现 usingscrollUntilVisible()
优于scrollIntoView()
,因为该元素可能尚未呈现,因此无法找到(请参阅https://flutter.dev/docs/cookbook/testing/integration/scrolling)。
scrollUntilVisible()
成功自动滚动屏幕并找到屏幕外的元素。但是,一旦找到,屏幕会出于某种原因自动跳回顶部,使元素再次脱离屏幕。这是怎么回事?
final myTextField = find.byValueKey('TextField');
final myListView = find.byValueKey('ListView');
test('Enter text into text field', () async {
await scrollUntilVisible(
myListView,
finder,
// To scroll down the list, provide a negative value to dyScroll.
// Ensure that this value is a small enough increment to
// scroll the item into view without potentially scrolling past it.
//
// To scroll through horizontal lists, provide a dxScroll
// property instead.
dyScroll: -100
);
await driver.tap(myTextField);
await driver.enterText('Hello world');
await driver.waitFor(find.text('Hello world'));
});