GithubHelp home page GithubHelp logo

Comments (6)

elianortega avatar elianortega commented on May 18, 2024

Hello @dipu0 can you share the TestBloc code?

from bloc.

dipu0 avatar dipu0 commented on May 18, 2024

Hello @dipu0 can you share the TestBloc code?
@elianortega hello here is my bloc code

class TestBloc extends Bloc<CartEvent, ItemState> {
  final Repository? repository;

  TestBloc({this.repository}) : super(ItemState()) {
    on<GetCartItemListEvent>(_getCartItemList);
    on<IncrementCartItemEvent>(_itemIncrease);
    on<DecrementCartItemEvent>(_itemDecrease);
  }

  void _getCartItemList(
      GetCartItemListEvent event, Emitter<ItemState> emit) async {
    emit(state.copyWith(status: CallbackStatus.loading, total: 0.0));
    try {
      List<ItemEntity?>? response = await repository!.getCartItemList();
      double total = 0;
      response!.forEach((element) {
        total = total + (double.parse(element!.productPrice!) * element.cartItemCount!);
      });
      emit(state.copyWith(
          status: CallbackStatus.success, response: response, total: total));
    } catch (e) {
      emit(state.copyWith(status: CallbackStatus.error));
    }
    emit(state.copyWith(status: CallbackStatus.initial));
  }

  void _itemIncrease(
      IncrementCartItemEvent event, Emitter<ItemState> emit) async {
    try{
      emit(state.copyWith(status: CallbackStatus.loading));
      List<ItemEntity> newCartList = [];
      double? total;
      for (int i = 0; i < state.response!.length; i++) {
        if (state.response![i]!.id == event.productId &&
            state.response![i]!.cartItemCount! < 99) {
          state.response![i]!.cartItemCount =
              state.response![i]!.cartItemCount! + 1;
          total =
              state.total! + double.parse(state.response![i]!.productPrice!);
        }
        newCartList.add(state.response![i]!);
      }
      bool? isAdded = await repository!.updateCartItem(newCartList);

      if(isAdded != null && isAdded == true){
        emit(state.copyWith(
            status: CallbackStatus.initial, response: newCartList, total: total));
      }
    }catch(e){
      emit(state.copyWith(status: CallbackStatus.initial));
    }
  }

  void _itemDecrease(
      DecrementCartItemEvent event, Emitter<ItemState> emit) async {
    try{
      emit(state.copyWith(status: CallbackStatus.loading));
      List<ItemEntity> newCartList = [];
      double? total;
      for (int i = 0; i < state.response!.length; i++) {
        if (state.response![i]!.id == event.productId &&
            state.response![i]!.cartItemCount! > 1) {
          state.response![i]!.cartItemCount = state.response![i]!.cartItemCount! - 1;
          total =
              state.total! - double.parse(state.response![i]!.productPrice!);
        }
        newCartList.add(state.response![i]!);
      }

      bool? isAdded = await repository!.updateCartItem(newCartList);
      if(isAdded != null && isAdded == true){
        emit(state.copyWith(
            status: CallbackStatus.initial, response: newCartList, total: total));
      }

    }catch(e){
      emit(state.copyWith(status: CallbackStatus.initial));
    }

  }
}

from bloc.

elianortega avatar elianortega commented on May 18, 2024

Hello @dipu0, is very hard to debug without syntax highlighting or running the code. But from a quick overview, I think something that could simplify your test is instead of adding the GetCartItemListEvent event to initialize the data before doing the actual test of DecrementCartItemEvent .

You can use the seed property from bloc test docs here.

seed is an optional Function that returns a state which will be used to seed the bloc before act is called.

Doing this will help you isolate the test scenario and analyze what is going on.

from bloc.

dipu0 avatar dipu0 commented on May 18, 2024

Hello @dipu0, is very hard to debug without syntax highlighting or running the code. But from a quick overview, I think something that could simplify your test is instead of adding the GetCartItemListEvent event to initialize the data before doing the actual test of DecrementCartItemEvent .

You can use the seed property from bloc test docs here.

seed is an optional Function that returns a state which will be used to seed the bloc before act is called.

Doing this will help you isolate the test scenario and analyze what is going on.

Already tried to use seed, but same!!!


class MockRepository extends Mock implements Repository {}

void main() {
  late MockRepository mockRepository;

  setUp(() {
    mockRepository = MockRepository();
    when(() => mockRepository.getCartItemList()).thenAnswer(
          (_) async => [
        ItemState(
          id: 1,
          productName: 'Product 1',
          productPrice: '10.00',
          cartItemCount: 2,
        ),
      ],
    );
    when(() => mockRepository.updateCartItem(any())).thenAnswer((_) async => true);
  });

  blocTest<TestBloc, ItemState>(
    'emits correct states when decrementing the cart item count and updating cart items',
    build: () => TestBloc(repository: mockRepository),
    act: (bloc) async {
      // Dispatch the GetCartItemListEvent to populate the initial state
      bloc.add(GetCartItemListEvent());

      // Wait for the GetCartItemListEvent to complete
      await Future.delayed(Duration(milliseconds: 200)); // Adjust the delay as needed

      // Verify the initial state after fetching cart items
      print("Initial State: ${bloc.state}");

      // Dispatch the DecrementCartItemEvent
      bloc.add(DecrementCartItemEvent(1));

      // Wait for the state to be emitted
      await expectLater(
        bloc.stream,
        emitsInOrder([
          ItemState(
            status: CallbackStatus.loading,
            response: [
              ItemState(
                id: 1,
                productName: 'Product 1',
                productPrice: '10.00',
                cartItemCount: 1,
              ),
            ],
            total: 20.0,
          ),
          ItemState(
            status: CallbackStatus.initial,
            response: [
              ItemState(
                id: 1,
                productName: 'Product 1',
                productPrice: '10.00',
                cartItemCount: 1, // Count should effet on this but it changers on previous cartItemCount too
              ),
            ],
            total: 10.0,
          ),
        ]),
      );
    },
  );
}

If I set the status to CallbackStatus.loading and itemCartCount: 2, it produces an error. If I set it to 1, the test case passes.

Expected: should do the following in order:
          • emit an event that
ItemState:<ItemState(CallbackStatus.loading, [ItemEntity{id: 1, productName: Product 1, productPrice: 10.00, cartItemCount: 2}], 20.0)>

          • emit an event that
ItemState:<ItemState(CallbackStatus.initial, [ItemEntity{id: 1, productName: Product 1, productPrice: 10.00, cartItemCount: 1}], 10.0)>

  Actual: <Instance of '_BroadcastStream<ItemState>'>

   Which: emitted 
• ItemState(CallbackStatus.loading, [ItemEntity{id: 1, productName: Product 1, productPrice: 10.00, cartItemCount: 1}], 20.0)

• ItemState(CallbackStatus.initial, [ItemEntity{id: 1, productName: Product 1, productPrice: 10.00, cartItemCount: 1}], 10.0)

which didn't emit an event that
ItemState:<ItemState(CallbackStatus.loading, [ItemEntity{id: 1, productName: Product 1, productPrice: 10.00, cartItemCount: 2}], 20.0)>

Here, and also in the previous test, the main problem was in the response (ItemEntity List). In the state, I have three things: CallbackStatus, a response which is a list of ItemEntity, and total. In every stage callback and total are correctly emitted, but in the response list, cartItemCount should start with 2 while CallbackStatus is loading and decrease by 1 in the last emit. However, cartItemCount stays the same as the last emit from the initial emits.

from bloc.

elianortega avatar elianortega commented on May 18, 2024

@dipu0 In that case, this is an issue probably with your implementation, as I said is very hard to analyze or debug with just the code snippets, can you please share a link to a minimal reproduction sample on GitHub or DartPad? It would be much easier to help if I can reproduce the issue locally, thanks!

from bloc.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.