Widget test failing when passing already created bloc instance to provider

Viewed 20

I'm passing the CartBloc instance to the BlocProvider. But the test is failing as the ListView widget is not found.

Below is the test code.

void main() {
  late MockCartRepository cartRepository;
  late MockSharedPreferenceService sharedPreferenceService;
  late AuthBloc authBloc;
  late MockUserRepository userRepository;
  late CartData cartData;
  late CartBloc cartBloc;

  setUp(() {
    cartData = CartData.fromJson(guestCartData);
    cartRepository = MockCartRepository();
    sharedPreferenceService = MockSharedPreferenceService();
    userRepository = MockUserRepository();
    authBloc = AuthBloc(
      service: sharedPreferenceService,
      userRepository: userRepository,
    );
    cartBloc = CartBloc(
      cartRepository: cartRepository,
      sharedPreferenceService: sharedPreferenceService,
      authBloc: authBloc,
    );
  });
  
  _pumpTestWidgetWithEvent(WidgetTester tester, CartEvent event) {
    return MaterialApp(
      home: BlocProvider(
        create: (_) => cartBloc..add(event),
        child: const CartView(),
      ),
    );
  }

  group('Testing cart view', () {
    testWidgets(
      'Adding item to cart',
      (WidgetTester tester) async {
        when(cartBloc.cartRepository.addToCart(
          cartId: cartData.id!,
          quantity: 1,
          variantId: cartData.lineItems!.physicalItems!.first.variantId!,
          productId: cartData.lineItems!.physicalItems!.first.productId!,
        )).thenAnswer((_) async => cartData);

        when(sharedPreferenceService.setString('cartId', cartData.id!))
            .thenAnswer((_) async => true);

        await tester.pumpWidget(
          _pumpTestWidgetWithEvent(
            tester,
            AddToCartEvent(
              cartId: cartData.id!,
              quantity: 1,
              variantId: cartData.lineItems!.physicalItems!.first.variantId!,
              productId: cartData.lineItems!.physicalItems!.first.productId!,
            ),
          ),
        );
        await tester.pumpAndSettle();
        expect(find.text('Cart'), findsOneWidget);
        expect(find.byType(ListView), findsOneWidget);
      },
    );
  });
}

The test passes when I pass a new instance of cart bloc as shown below.

_pumpTestWidgetWithEvent(WidgetTester tester, CartEvent event) {
    return MaterialApp(
      home: BlocProvider(
        create: (_) => CartBloc(
          cartRepository: cartRepository,
          sharedPreferenceService: sharedPreferenceService,
          authBloc: authBloc,
        )..add(event),
        child: const CartView(),
      ),
    );
  }

Why is this happening?

I've also tried using BlocProvider.value and passing cartBloc as value. But this also failing.

0 Answers
Related