Flutter test find by sub text

Viewed 2232

Is it possible to assert a test if the certain text is found either as full string match or as a sub string of other text?

I want the following test to pass as long as the string Foo is found anywhere, even as sub string of other strings. What should I change?

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);
  });
}

So far:

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 Answers

You can use 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);
  });
}

Replace:

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

with:

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);

You will first find Text widget, then check for substring in the Text string

Related