Comments (6)
Hello @dipu0 can you share the TestBloc
code?
from bloc.
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.
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.
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 ofDecrementCartItemEvent
.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.
@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)
- ReplayBloc function onTransition() handles event _Undo instead of user defined event HOT 2
- fix: In Flutter v3.16.4 stable the fromJson method stopped working HOT 1
- Flutter Bloc With Alert Dialogs throws an error HOT 4
- why my code will result in error? HOT 2
- BlocBuilder not getting called after creating new task, ListView still displays old data HOT 2
- question: bloc with many datasets HOT 26
- feat: Use with Freezed HOT 1
- BlocBuilder only build once and stop rebuild with subsequent emit HOT 6
- fix: hydrated bloc stopped persisting state after update (^9.1.3) HOT 6
- Cannot override EventHandler (Bug?) HOT 1
- fix: The "New Bloc/Cubit" option is not showing in VSCode Extensions HOT 2
- feate
- feat: why not fusion bloc_concurrency package into bloc HOT 2
- feat: BlocListener that trigger once but with return specific prop like BlocSelector HOT 3
- Help:add a event but state not change HOT 3
- TabBarView bug with Scrollable.ensureVisible and bloc HOT 4
- docs: Multiple cubits in single page HOT 3
- feat: Support time manipulation in bloc_test with clock/fakeAsync HOT 2
- docs(bloc): bloc effects
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from bloc.