Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for substring in Text widget

Tags:

flutter

dart

Normally to find an entire string you can use find.text() like this:

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

What about finding a substring in a Text widget? Say there was text of 'text to find', and we just wanted to check that 'to' is a part of a Text widget.

like image 579
S.D. Avatar asked Nov 26 '18 00:11

S.D.


2 Answers

By using find.byWidgetPredicate, you can specify your own validation predicate and thus check everything you want like a substring of the text.

eg :

expect(find.byWidgetPredicate((widget) {
  if (widget is Text) {
    final Text textWidget = widget;
    if (textWidget.data != null)
      return textWidget.data.contains('mySubstr');
    return textWidget.textSpan.toPlainText().contains('mySubstr');
  } 
  return false;
}), findsOneWidget);
like image 139
Muldec Avatar answered Oct 21 '22 00:10

Muldec


Now using dart extension methods we can write more readable tests.

First, add a new method to the CommonFinders class:

extension CustomFinders on CommonFinders {
  Finder textMatch(Pattern pattern, {bool skipOffstage = true}) =>
      _PatternMatchFinder(pattern, skipOffstage: skipOffstage);
}

class _PatternMatchFinder extends MatchFinder {
  _PatternMatchFinder(this.pattern, {bool skipOffstage = true}) : super(skipOffstage: skipOffstage);

  final Pattern pattern;

  @override
  String get description => 'textMatch "$pattern"';

  @override
  bool matches(Element candidate) {
    final Widget widget = candidate.widget;
    if (widget is Text) {
      if (widget.data != null) return pattern.allMatches(widget.data).isNotEmpty;
      return pattern.allMatches(widget.textSpan.toPlainText()).isNotEmpty;
    } else if (widget is EditableText) {
      return pattern.allMatches(widget.controller.text).isNotEmpty;
    }
    return false;
  }
}

And now our tests look like this:

expect(find.textMatch('Back'), findsOneWidget);
expect(find.textMatch(RegExp(r'\s*Back.*')), findsOneWidget);
like image 26
Spatz Avatar answered Oct 21 '22 00:10

Spatz