颤振测试按子文本查找

时间:2020-06-02 13:35:47

标签: unit-testing flutter dart

是否可以确定某个文本是作为完整字符串匹配还是作为其他文本的子字符串找到?

我希望只要在任何地方都可以找到字符串Foo,即使作为其他字符串的子字符串,也要通过以下测试。我应该改变什么?

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
  testWidgets('Find sub text', (WidgetTester tester) async {
    await tester.pumpWidget(Text('Error code is Foo', textDirection: TextDirection.ltr));
    expect(find.text('Error code is Foo'), findsOneWidget);
    expect(find.text('Foo'), findsOneWidget);
  });
}

到目前为止:

The following TestFailure object was thrown running a test:
  Expected: exactly one matching node in the widget tree
  Actual: _TextFinder:<zero widgets with text "Foo" (ignoring offstage widgets)>
   Which: means none were found but one was expected

2 个答案:

答案 0 :(得分:3)

替换:

expect(find.text('Foo'), findsOneWidget);

具有:

expect(find.byWidgetPredicate((widget) {
  if (widget is Text) {
    final Text textWidget = widget;
    if (textWidget.data != null) return textWidget.data.contains('Foo');
    return textWidget.textSpan.toPlainText().contains('Foo');
  }
  return false;
}), findsOneWidget);

您将首先找到“文本”小部件,然后检查“文本”字符串中的子字符串

答案 1 :(得分:0)

您可以使用find.textContaining

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
  testWidgets('Find sub text', (WidgetTester tester) async {
    await tester.pumpWidget(Text('Error code is Foo', textDirection: TextDirection.ltr));
    expect(find.text('Error code is Foo'), findsOneWidget);
    expect(find.textContaining('Foo'), findsOneWidget);
  });
}