How to extract Left or Right easily from Either type in Dart (Dartz)
I am looking to extract a value easily from a method that return a type Either<Exception, Object>
.
I am doing some tests but unable to test easily the return of my methods.
For example:
final Either<ServerException, TokenModel> result = await repository.getToken(...);
To test I am able to do that
expect(result, equals(Right(tokenModelExpected))); // => OK
Now how can I retrieve the result directly?
final TokenModel modelRetrieved = Left(result); ==> Not working..
I found that I have to cast like that:
final TokenModel modelRetrieved = (result as Left).value; ==> But I have some linter complain, that telling me that I shouldn't do as to cast on object...
Also I would like to test the exception but it's not working, for example:
expect(result, equals(Left(ServerException()))); // => KO
So I tried this
expect(Left(ServerException()), equals(Left(ServerException()))); // => KO as well, because it says that the instances are different.
Ok here the solutions of my problems:
To extract/retrieve the data
final Either<ServerException, TokenModel> result = await repository.getToken(...);
result.fold(
(exception) => DoWhatYouWantWithException,
(tokenModel) => DoWhatYouWantWithModel
);
//Other way to 'extract' the data
if (result.isRight()) {
final TokenModel tokenModel = result.getOrElse(null);
}
To test the exception
//You can extract it from below, or test it directly with the type
expect(() => result, throwsA(isInstanceOf<ServerException>()));
I can't post a comment... But maybe you could look at this post. It's not the same language, but looks like it's the same behaviour.
Good luck.