Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter test find by sub text

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
like image 529
TSR Avatar asked Jun 02 '20 13:06

TSR


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);
  });
}
like image 50
Valentin Vignal Avatar answered Oct 16 '22 02:10

Valentin Vignal


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

like image 41
camillo777 Avatar answered Oct 16 '22 00:10

camillo777