I have Future function called addRating that add data to Firestore, I am new to testing in flutter, how do I achieve it?
Function I want to test:
Future<void> addRating(RatingModel rating) async {
await _firestore.collection('rating').doc(rating.ratingId).set(rating.toJson());
}
What I have tried:
final firestore = FakeFirebaseFirestore();
test('can add to firestore', () async{
RatingRepository ratingRepository = RatingRepository(firestore: firestore);
RatingModel model = RatingModel(feedback: 'test', merchantId: '1', orderId: '1', rating: 1, ratingId: '1');
await expectLater(()async{await ratingRepository.addRating(model);}, isNull);
});
CodePudding user response:
You are almost there. The idea of using await
is correct. You could do the following
final firestore = FakeFirebaseFirestore();
test('can add to firestore', () async{
RatingRepository ratingRepository = RatingRepository(firestore: firestore);
RatingModel model = RatingModel(feedback: 'test', merchantId: '1', orderId: '1', rating: 1, ratingId: '1');
await ratingRepository.addRating(model);
expect(...); // Whatever condition should be fullfilled afterwards.
});
This works because the test function itslef is marked as async
, allowing you to use await like that inside the function body.
The last line of course depends on your use case. Should a rating be increased? Should it be stored somewhere?
CodePudding user response:
I think If you are expecting nothing then you just need to verify that the function is called:
verify(()async{await ratingRepository.addRating(model);})