Search code examples
flutterunit-testingfreezed

flutter freezed : equals type of object is not same


I am using freezed to make object from json :

@freezed
class UserMessagesResponseModel with _$UserMessagesResponseModel {
  const factory UserMessagesResponseModel({
    final Data? data,
  }) = _UserMessagesResponseModel;

  factory UserMessagesResponseModel.fromJson(final Map<String, dynamic> json) =>
      _$UserMessagesResponseModelFromJson(json);
}

@freezed
class Data with _$Data {
  const factory Data({
    final Messages? messages,
  }) = _Data;

  factory Data.fromJson(final Map<String, dynamic> json) =>
      _$DataFromJson(json);
}...

Now I am trying to make a test and chack type of created object:

test('should return a valid model', () async {
  final jsonMap =
      json.decode(fixture('message.json')) as Map<String, dynamic>;

  final result = UserMessagesResponseModel.fromJson(
    jsonMap,
  );
    
  expect(result, equals(UserMessagesResponseModel));
});

why I got error:

Expected: Type:<UserMessagesResponseModel>
  Actual: _$_UserMessagesResponseModel:<UserMessagesResponseModel...

Freezed Not make same type ? How can I check type ?

I also used:

expect(result, isA<UserMessagesResponseModel>);

but I got this:

Expected: <Closure: () => TypeMatcher<UserMessagesResponseModel> from Function 'isA': static.>
  Actual: _$_UserMessagesResponseModel:<UserMessagesResponseModel

Solution

  • The first example

    expect(result, equals(UserMessagesResponseModel));
    

    doesn't work because result is an instance and UserMessagesResponseModel is a type, you should use isA.

    But on the second example I use isA and it still doesn't work!

    You missed the () after isA, I believe that is why it does't work.

    from this:

    expect(result, isA<UserMessagesResponseModel>);
    

    to this:

    expect(result, isA<UserMessagesResponseModel>());