Flutter BLoC Testing

Issue

I am using the flutter_bloc library and trying to do unit testing.
I am doing this pretty much as explained in this tutorial and it’s doing fine.

However, if a BlocState which extends Equatable (which required) has many properties or large list of items which extends Equatable, as well with their props[] defined as required.

This makes hard for the expectLater() to match proper emitted states because it tries to match the exact instance with its content and not only the state type or instance of.

For example:

Consider the following State class:

class BlocState extends Equatable{
     final List<String> data;
     BlocState({this.data});

     @override
     List<Object> get props => [data];
}

Then for emitted state like this:

List<String> data = ['Mark', 'Mike', 'John']
BlocState({data: data}); 

This expectLater will fail

 expectLater(
    bloc,
    emitsInOrder([BlocState(),]), //This will fail as the state does't equals exactly to the real state
  )

And this one will pass:

expectLater(
    bloc,
    emitsInOrder([BlocState(data: ['Mark', 'Mike', 'John']),]), //This will pass 
  )

On such simple state it’s fine to verify exact content, but if the list will have 100 items how it can be tested?

Is there a way to verify just the instance type without the content?

Solution

I’m not sure if this is what you mean, but you could do something like this:

List<String> myData = ['Mark', 'Mike', 'John', 'AddAsManyAsYouLike'];
bloc.add(SomeEvent());

expectLater(
    bloc,
    emitsInOrder([BlocState(data: myData)])
)

Or if you only care about the right type you could use isA<>()

expectLater(
    bloc,
    emitsInOrder([isA<BlocState>()])
)

Answered By – Er1

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *