|
| 1 | +import 'package:ecommerce_app/src/features/cart/domain/item.dart'; |
| 2 | +import 'package:ecommerce_app/src/features/cart/presentation/add_to_cart/add_to_cart_controller.dart'; |
| 3 | +import 'package:flutter_riverpod/flutter_riverpod.dart'; |
| 4 | +import 'package:flutter_test/flutter_test.dart'; |
| 5 | +import 'package:mocktail/mocktail.dart'; |
| 6 | + |
| 7 | +import '../../../../mocks.dart'; |
| 8 | + |
| 9 | +void main() { |
| 10 | + const productId = '1'; |
| 11 | + group('addItem', () { |
| 12 | + test('item added with quantity = 2, success', () async { |
| 13 | + // setup |
| 14 | + const quantity = 2; |
| 15 | + const item = Item(productId: productId, quantity: quantity); |
| 16 | + final cartService = MockCartService(); |
| 17 | + when(() => cartService.addItem(item)).thenAnswer( |
| 18 | + (_) => Future.value(null), |
| 19 | + ); |
| 20 | + // run & verify |
| 21 | + final controller = AddToCartController(cartService: cartService); |
| 22 | + expect( |
| 23 | + controller.state, |
| 24 | + const AsyncData(1), |
| 25 | + ); |
| 26 | + controller.updateQuantity(quantity); |
| 27 | + expect( |
| 28 | + controller.state, |
| 29 | + const AsyncData(2), |
| 30 | + ); |
| 31 | + // * if desired, use expectLater and emitsInOrder here to check that |
| 32 | + // * addItems emits two values |
| 33 | + await controller.addItem(productId); |
| 34 | + verify(() => cartService.addItem(item)).called(1); |
| 35 | + // check that quantity goes back to 1 after adding an item |
| 36 | + expect( |
| 37 | + controller.state, |
| 38 | + const AsyncData(1), |
| 39 | + ); |
| 40 | + }); |
| 41 | + |
| 42 | + test('item added with quantity = 2, failure', () async { |
| 43 | + const quantity = 2; |
| 44 | + const item = Item(productId: productId, quantity: quantity); |
| 45 | + final cartService = MockCartService(); |
| 46 | + when(() => cartService.addItem(item)) |
| 47 | + .thenThrow((_) => Exception('Connection failed')); |
| 48 | + final controller = AddToCartController(cartService: cartService); |
| 49 | + expect( |
| 50 | + controller.state, |
| 51 | + const AsyncData(1), |
| 52 | + ); |
| 53 | + controller.updateQuantity(quantity); |
| 54 | + expect( |
| 55 | + controller.state, |
| 56 | + const AsyncData(2), |
| 57 | + ); |
| 58 | + // * if desired, use expectLater and emitsInOrder here to check that |
| 59 | + // * addItems emits two values |
| 60 | + await controller.addItem(productId); |
| 61 | + verify(() => cartService.addItem(item)).called(1); |
| 62 | + // check that quantity goes back to 1 after adding an item |
| 63 | + expect( |
| 64 | + controller.state, |
| 65 | + predicate<AsyncValue<int>>( |
| 66 | + (value) { |
| 67 | + expect(value.hasError, true); |
| 68 | + return true; |
| 69 | + }, |
| 70 | + ), |
| 71 | + ); |
| 72 | + }); |
| 73 | + }); |
| 74 | +} |
0 commit comments