Flutter: How to test a widgets who contains a StreamBuilder?

440

Is it necessary to test this StreamBuilder?

This is subjective. Generally if there is anything that you feel is critical to the functionality of your app, then its better to write a test for it to ensure it works/behaves as expected always.

How can I mock the stream and test these widgets ?

There are tons of resources online to achieve this. Maybe have a look at this?

Share:
440
Cem Kaan
Author by

Cem Kaan

Developer and consumer-friendly design built for practical real-world use cases

Updated on December 25, 2022

Comments

  • Cem Kaan
    Cem Kaan over 1 year

    I'm new on Flutter and I want to add Widgets tests to my app. But I have some problems and questions about widget tests a little more complex than flutter documentation. Indeed i have a Scaffold widget with this body :

    body: StreamBuilder<List<UserData>> (
            stream: DatabaseService().searchUser(searchValue),
            builder: (context, snapshot) {
              if (snapshot.hasData && searchValue.length >= 3){
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      onTap: () {
                        Navigator.pushReplacementNamed(context, '/friends/search/details', arguments: snapshot.data[index]);
                      },
                      title: Text(snapshot.data[index].name),
                    );
                  }
                );
              }
              return Center();
            },
          )
    

    The first question is:

    Is it necessary to test this StreamBuilder?

    And if yes: How can I mock the stream and test these widgets ?

  • Admin
    Admin over 3 years
    Thanks, I looked at this example, but the builder is defined in test, how can I get the builder of my Scaffold widget ?
  • Joy Terence
    Joy Terence over 3 years
    You could mimic the similar code and then with expect verify the widgets.