简体   繁体   中英

Flutter - how to get Text widget on widget test

I'm trying to create a simple widget test in Flutter. I have a custom widget that receives some values, composes a string and shows a Text with that string. I got to create the widget and it works, but I'm having trouble reading the value of the Text component to assert that the generated text is correct.

I created a simple test that illustrates the issue. I want to get the text value, which is "text". I tried several ways, if I get the finder asString() I could interpret the string to get the value, but I don't consider that a good solution. I wanted to read the component as a Text so that I have access to all the properties.

So, how would I read the Text widget so that I can access the data property?

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('my first widget test', (WidgetTester tester) async {

    await tester
        .pumpWidget(MaterialApp(home: Text("text", key: Key('unit_text'))));

    // This works and prints: (Text-[<'unit_text'>]("text"))
    var finder = find.byKey(Key("unit_text"));
    print(finder.evaluate().first);

    // This also works and prints: (Text-[<'unit_text'>]("text"))
    var finderByType = find.byType(Text);
    print(finderByType.evaluate().first);

    // This returns empty
    print(finder.first.evaluate().whereType<Text>());

    // This throws: type 'StatelessElement' is not a subtype of type 'Text' in type cast
    print(finder.first.evaluate().cast<Text>().first);

  });
}

I got it working. I had to access the widget property of the Element, and then cast it as text:

var text = finder.evaluate().single.widget as Text;
print(text.data);

Please check this simple example.

testWidgets('Test name', (WidgetTester tester) async {

// findig the widget
var textFind = find.text("text_of_field");

// checking widget present or not
expect(textFind, findsOneWidget);

//getting Text object
Text text = tester.firstWidget(textFind);

// validating properies
expect(text.style.color, Colors.black);
...
...

}

You can use find.text

https://flutter.io/docs/cookbook/testing/widget/finders#1-find-a-text-widget

testWidgets('finds a Text Widget', (WidgetTester tester) async {
  // Build an App with a Text Widget that displays the letter 'H'
  await tester.pumpWidget(MaterialApp(
    home: Scaffold(
      body: Text('H'),
    ),
  ));

  // Find a Widget that displays the letter 'H'
  expect(find.text('H'), findsOneWidget);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM