diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index be8cff37..289a7a26 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -30,6 +30,7 @@ import 'package:eatvio_app/features/chat/utils/chat_counterpart_utils.dart'; import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart'; import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart'; import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart'; import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart'; import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart'; import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart'; @@ -72,6 +73,10 @@ class _ChatScreenState extends State { String? get conversationUuid => _effectiveUuid ?? widget.uuid; + bool _canStartVideoCall(ChosenPlanModel? chosenPlan) { + return chosenPlan?.chosenPlanState.allowsVideoCall ?? false; + } + void _onHide() { chatRoomCubit.cancelTimer(); } @@ -205,6 +210,7 @@ class _ChatScreenState extends State { chosenPlan != null && chosenPlan.chosenPlanState != ChosenPlanStateEnum.stateCanceledByTheInitiator; + final showVideoCallButton = _canStartVideoCall(chosenPlan); return Scaffold( resizeToAvoidBottomInset: true, @@ -300,12 +306,14 @@ class _ChatScreenState extends State { ), ), actions: [ - Padding( - padding: const EdgeInsetsDirectional.only(end: 8), - child: _ChatHeaderVideoCallButton( - onPressed: () => _openVideoCall(context, state, chatCounterpart), + if (showVideoCallButton) + Padding( + padding: const EdgeInsetsDirectional.only(end: 8), + child: _ChatHeaderVideoCallButton( + onPressed: () => + _openVideoCall(context, state, chatCounterpart), + ), ), - ), ], ), body: SafeArea( @@ -324,8 +332,7 @@ class _ChatScreenState extends State { InfoByOrderScreen.path, extra: { 'planId': chosenPlan?.id, - 'customerSlug': - state.chatRoom.users.receiver.slug, + 'customerSlug': state.chatRoom.users.receiver.slug, }, ); return; @@ -1018,7 +1025,8 @@ class _ChatScreenState extends State { required bool? amIConsultant, }) { if (message.type == ChatMessageType.videoCallStarted && - !isCurrentUserAuthor) { + !isCurrentUserAuthor && + _canStartVideoCall(state.chatRoom.chosenPlan)) { return VideoCallChatMessageWidget( text: message.data.trim(), sendTime: message.updatedAt, diff --git a/lib/features/diary/presentation/bloc/diary_cubit.dart b/lib/features/diary/presentation/bloc/diary_cubit.dart index 289e3ecf..35790f37 100644 --- a/lib/features/diary/presentation/bloc/diary_cubit.dart +++ b/lib/features/diary/presentation/bloc/diary_cubit.dart @@ -14,6 +14,7 @@ import 'package:eatvio_app/features/diary/models/nutrition_model.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/glossary/models/glossary_model.dart'; import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; @@ -38,6 +39,8 @@ class DiaryCubit extends Cubit { final ChatRepository chatRepository; final SettingsRepository settingsRepository; int? diaryId; + int _fetchGeneration = 0; + DiaryCubit({ required this.chatRepository, required this.diaryRepository, @@ -61,14 +64,21 @@ class DiaryCubit extends Cubit { selectedDay = date; } + bool _isCurrentFetch(int generation) => generation == _fetchGeneration; + Future setSelectedDay(DateTime day) async { final prevDay = selectedDay; final prevMeal = selectedMeal; selectedDay = day; selectedMeal = 1; - final canSelect = await fetchDiaryV2(needLoading: true); + final generation = ++_fetchGeneration; + final canSelect = await fetchDiaryV2(needLoading: true, generation: generation); - if (!canSelect) { + if (!_isCurrentFetch(generation)) { + return false; + } + + if (!canSelect && state is! DiaryStateError) { selectedDay = prevDay; selectedMeal = prevMeal; } @@ -76,22 +86,33 @@ class DiaryCubit extends Cubit { return canSelect; } - Future fetchDiaryV2({bool needLoading = false, int? diaryId}) async { + Future fetchDiaryV2({bool needLoading = false, int? diaryId, int? generation}) async { + final request = generation ?? ++_fetchGeneration; + final requestedDay = selectedDay; final currentState = state; try { + if (!_isCurrentFetch(request)) { + return false; + } if (needLoading) { emit(const DiaryState.loading()); } if (diaryId != null) { final diaryDayById = await diaryRepository.getDiaryDay(diaryId); + if (!_isCurrentFetch(request)) { + return false; + } final diaryEntity = diaryDayById.toEntity(); if (diaryEntity != null) { - setDiary(diaryDay: diaryEntity, diaryId: diaryId); - return true; + await setDiary(diaryDay: diaryEntity, diaryId: diaryId, generation: request); + return _isCurrentFetch(request); } } - final diaryDay = await getDiary(); + final diaryDay = await getDiary(day: requestedDay); + if (!_isCurrentFetch(request)) { + return false; + } if (diaryDay == null) { emit(const DiaryState.error(errorMessage: 'Diary not found')); return true; @@ -99,16 +120,26 @@ class DiaryCubit extends Cubit { final diaryEntity = diaryDay.toEntity(); if (diaryEntity != null) { - setDiary(diaryDay: diaryEntity, diaryId: diaryId); - return true; + await setDiary(diaryDay: diaryEntity, diaryId: diaryId, generation: request); + return _isCurrentFetch(request); } - if (diaryDay.typeOfDiary.hasChosenDiet == true && diaryDay.typeOfDiary.diaryState == null) { - setDiaryForDietOnly(diaryDay.toDiaryFutureDayEntity()); - return true; + + if (_isUnsavedDietPreview(diaryDay)) { + final shown = await setDiaryForDietOnly(diaryDay.toDiaryFutureDayEntity(), generation: request); + if (!_isCurrentFetch(request)) { + return false; + } + if (!shown && state is DiaryStateLoading) { + emit(currentState); + } + return shown; } emit(currentState); return false; } catch (e, st) { + if (!_isCurrentFetch(request)) { + return false; + } await reportFrom(e, st, this); log(e.toString(), stackTrace: st); emit(DiaryState.error(errorMessage: e.toString())); @@ -129,17 +160,18 @@ class DiaryCubit extends Cubit { } } - Future getDiary() async { + Future getDiary({DateTime? day}) async { + final requestedDay = (day ?? selectedDay).toISO8601WithTimeZoneOffset(); try { - await diaryRepository.createDiaryDay(day: selectedDay.toISO8601WithTimeZoneOffset()); - final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset()); + await diaryRepository.createDiaryDay(day: requestedDay); + final diaryDay = await diaryRepository.getDiaryDayV2(day: requestedDay); return diaryDay; } catch (e, st) { await reportFrom(e, st, this); log(e.toString(), stackTrace: st); if (e is DioException) { if (e.response?.statusCode == 422) { - final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset()); + final diaryDay = await diaryRepository.getDiaryDayV2(day: requestedDay); return diaryDay; } } @@ -157,92 +189,83 @@ class DiaryCubit extends Cubit { } } - Future setDiaryForDietOnly(DiaryFutureDietDayEntity diaryDay) async { - if (!diaryDay.typeOfDiary.hasChosenDiet) { + bool _isUnsavedDietPreview(DiaryDayModel diaryDay) { + final diaryState = diaryDay.typeOfDiary.diaryState; + final dayNotStarted = diaryState == null || diaryState == DiaryStateEnum.init; + return diaryDay.typeOfDiary.hasChosenDiet && dayNotStarted; + } + + Future setDiaryForDietOnly(DiaryFutureDietDayEntity diaryDay, {int? generation}) async { + final dietId = diaryDay.diet?.id; + final dayOfChosenDiet = diaryDay.dayOfChosenDiet; + if (!diaryDay.typeOfDiary.hasChosenDiet || dietId == null || dayOfChosenDiet == null) { + return false; + } + if (generation != null && !_isCurrentFetch(generation)) { return false; } emit(const DiaryState.loading()); try { - if (diaryDay.diet?.id != null && diaryDay.dayOfChosenDiet != null) { - final diet = await dietRepository.getDiet((diaryDay.diet?.id)!); - final meals = diet.dailySchedule[diaryDay.dayOfChosenDiet]; - final firstMealPortions = meals?[1]?.values.map((elem) { - return PortionModel( - id: 0, - productName: elem.name, - quantity: elem.quantity, - portion: elem.portion.getValue(), - fromDiet: true, - portionState: PortionState.filledDiet, - ); - }).toList(); + final diet = await dietRepository.getDiet(dietId); + if (generation != null && !_isCurrentFetch(generation)) { + return false; + } + final meals = diet.dailySchedule[dayOfChosenDiet]; + List portionsOfMeal(int mealNumber) { + return meals?[mealNumber]?.values.map(_portionFromDiet).toList() ?? []; + } - final secondMealPortions = meals?[2]?.values.map((elem) { - return PortionModel( - id: 0, - productName: elem.name, - quantity: elem.quantity, - portion: elem.portion.getValue(), - fromDiet: true, - portionState: PortionState.filledDiet, - ); - }).toList(); + MealModel meal(int mealNumber) { + return MealModel(id: 0, time: '0', typeNumber: mealNumber, satiety: 0, mood: 0, portions: portionsOfMeal(mealNumber), photos: []); + } - final thirdMealPortions = meals?[3]?.values.map((elem) { - return PortionModel( - id: 0, - productName: elem.name, - quantity: elem.quantity, - portion: elem.portion.getValue(), - fromDiet: true, - portionState: PortionState.filledDiet, - ); - }).toList(); - - final fourthMealPortions = meals?[4]?.values.map((elem) { - return PortionModel( - id: 0, - productName: elem.name, - quantity: elem.quantity, - portion: elem.portion.getValue(), - fromDiet: true, - portionState: PortionState.filledDiet, - ); - }).toList(); - - final fifthMealPortions = meals?[5]?.values.map((elem) { - return PortionModel( - id: 0, - productName: elem.name, - quantity: elem.quantity, - portion: elem.portion.getValue(), - fromDiet: true, - portionState: PortionState.filledDiet, - ); - }).toList(); - final firstMeal = MealModel(id: 0, time: '0', typeNumber: 1, satiety: 0, mood: 0, portions: firstMealPortions ?? [], photos: []); - final secondMeal = MealModel(id: 0, time: '0', typeNumber: 2, satiety: 0, mood: 0, portions: secondMealPortions ?? [], photos: []); - final thirdMeal = MealModel(id: 0, time: '0', typeNumber: 3, satiety: 0, mood: 0, portions: thirdMealPortions ?? [], photos: []); - final fourthMeal = MealModel(id: 0, time: '0', typeNumber: 4, satiety: 0, mood: 0, portions: fourthMealPortions ?? [], photos: []); - final fifthMeal = MealModel(id: 0, time: '0', typeNumber: 5, satiety: 0, mood: 0, portions: fifthMealPortions ?? [], photos: []); emit( DiaryState.loadedTomorrowWithDiet( - diary: diaryDay.copyWith(meals: [firstMeal, secondMeal, thirdMeal, fourthMeal, fifthMeal]), + diary: diaryDay.copyWith(meals: [meal(1), meal(2), meal(3), meal(4), meal(5)]), selectedDay: selectedDay, selectedMeal: selectedMeal, ), ); - return true; - } - return false; + return true; } catch (e, st) { + if (generation != null && !_isCurrentFetch(generation)) { + return false; + } await reportFrom(e, st, this); emit(DiaryState.error(errorMessage: e.toString())); return false; } } - Future setDiary({int? diaryId, required DiaryDayEntity diaryDay}) async { + PortionModel _portionFromDiet(DailySchedule elem) { + final nutrition = elem.dailyNutrition; + final per100 = elem.portion == Portion.grams && elem.quantity > 0 ? 100 / elem.quantity : 1.0; + return PortionModel( + id: 0, + productNutritionalValueId: elem.productNutritionalValueId, + productCaloriesInfo: nutrition == null + ? null + : ProductCaloriesInfoModel( + id: elem.productNutritionalValueId ?? 0, + productName: elem.name, + calories: nutrition.energy * per100, + proteins: nutrition.proteins * per100, + fats: nutrition.fats * per100, + carbohydrates: nutrition.carbohydrates * per100, + energyOnPortion: nutrition.energy, + proteinsOnPortion: nutrition.proteins, + fatsOnPortion: nutrition.fats, + carbohydratesOnPortion: nutrition.carbohydrates, + ), + productName: elem.name, + quantity: elem.quantity, + portion: elem.portion.getValue(), + fromDiet: true, + portionState: PortionState.filledDiet, + ); + } + + Future setDiary({int? diaryId, required DiaryDayEntity diaryDay, int? generation}) async { this.diaryId ??= diaryId; final isConsultantView = this.diaryId != null; try { @@ -270,6 +293,9 @@ class DiaryCubit extends Cubit { currentPlanDay = consultantReview.currentPlanDay; } final nutrition = await getNutrition(diaryDay.id); + if (generation != null && !_isCurrentFetch(generation)) { + return; + } final isDiaryFinished = diaryDay.typeOfDiary.diaryState == DiaryStateEnum.finished || diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayFinished; @@ -295,6 +321,9 @@ class DiaryCubit extends Cubit { ), ); } catch (e, st) { + if (generation != null && !_isCurrentFetch(generation)) { + return; + } await reportFrom(e, st, this); log(e.toString(), stackTrace: st); emit(DiaryState.error(errorMessage: e.toString())); diff --git a/lib/features/diary/presentation/widgets/calendar_widget.dart b/lib/features/diary/presentation/widgets/calendar_widget.dart index 0ad135f4..3b386d67 100644 --- a/lib/features/diary/presentation/widgets/calendar_widget.dart +++ b/lib/features/diary/presentation/widgets/calendar_widget.dart @@ -22,12 +22,26 @@ class _CalendarWidgetState extends State { CalendarFormat _calendarFormat = CalendarFormat.week; DateTime _focusedDay = DateTime.now(); DateTime _selectedDay = DateTime.now(); + DateTime? _dayFromState(DiaryState state) { + if (state is DiaryStateLoaded) { + return state.selectedDay; + } + if (state is DiaryStateLoadedTomorrowWithDiet) { + return state.selectedDay; + } + return null; + } + @override void initState() { super.initState(); + final selected = _dayFromState(context.read().state); if (widget.date != null) { _selectedDay = widget.date!; _focusedDay = widget.date!; + } else if (selected != null) { + _selectedDay = selected; + _focusedDay = selected; } } @@ -47,9 +61,11 @@ class _CalendarWidgetState extends State { final daysOfWeekHeight = _scaledDaysOfWeekHeight(context); return BlocConsumer( listener: (BuildContext context, DiaryState state) { - if (state is DiaryStateLoaded) { + final selected = _dayFromState(state); + if (selected != null) { setState(() { - _selectedDay = state.selectedDay; + _selectedDay = selected; + _focusedDay = selected; }); } }, @@ -77,8 +93,12 @@ class _CalendarWidgetState extends State { _selectedDay = selectedDay; _focusedDay = focusedDay; }); - final canOpenNextDay = await context.read().setSelectedDay(selectedDay); - if (!canOpenNextDay && context.mounted) { + final cubit = context.read(); + final canOpenNextDay = await cubit.setSelectedDay(selectedDay); + if (!context.mounted || cubit.state is DiaryStateError) { + return; + } + if (!canOpenNextDay) { showErrorDialog(context, title: s.want_to_see_tomorrow, description: s.can_not_see_next_day); setState(() { _selectedDay = previousSelectedDay; diff --git a/lib/features/plans/enums/chosen_plan_state_enum.dart b/lib/features/plans/enums/chosen_plan_state_enum.dart index fad8736c..39ece132 100644 --- a/lib/features/plans/enums/chosen_plan_state_enum.dart +++ b/lib/features/plans/enums/chosen_plan_state_enum.dart @@ -88,6 +88,18 @@ enum ChosenPlanStateEnum { } } + bool get allowsVideoCall { + switch (this) { + case ChosenPlanStateEnum.stateCanceledByTheInitiator: + case ChosenPlanStateEnum.statePaymentFailed: + case ChosenPlanStateEnum.stateDone: + case ChosenPlanStateEnum.stateChargeWasCollected: + return false; + default: + return true; + } + } + static List getActiveStates() { return [ ChosenPlanStateEnum.statePaid, diff --git a/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart b/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart index a8479ffc..b5690c68 100644 --- a/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart +++ b/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart @@ -80,29 +80,33 @@ class SettingsCubit extends Cubit { } } - Future updateProfileDetails({ + Future updateProfileDetails({ required ProfileDetailsModel profileDetailsModel, }) async { try { await settingsRepository.updateProfileDetails( profileDetailsModel: profileDetailsModel, ); + return true; } catch (e, st) { await reportFrom(e, st, this); + return false; } finally { await init(); } } - Future updateProfileSettings({ + Future updateProfileSettings({ required ProfileSettingsModel profileSettingsModel, }) async { try { await settingsRepository.updateProfileSettings( profileSettingsModel: profileSettingsModel, ); + return true; } catch (e, st) { await reportFrom(e, st, this); + return false; } finally { await init(); } diff --git a/lib/features/settings/presentation/pages/general_info_screen.dart b/lib/features/settings/presentation/pages/general_info_screen.dart index 2396a54c..4340e573 100644 --- a/lib/features/settings/presentation/pages/general_info_screen.dart +++ b/lib/features/settings/presentation/pages/general_info_screen.dart @@ -1,5 +1,6 @@ import 'package:eatvio_app/core/data/selectionPopupModel/selection_popup_model.dart'; import 'package:eatvio_app/core/utils/date_time_utils.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_drop_down.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; @@ -10,6 +11,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:material_ui/material_ui.dart'; import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:go_router/go_router.dart'; class GeneralInfoScreen extends StatefulWidget { final SettingsEntity settingsEntity; @@ -233,7 +235,7 @@ class _GeneralInfoScreenState extends State { setState(() { isLoading = true; }); - await widget.settingsEntity.settingsCubit.updateProfileDetails( + final detailsSaved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( firstName: firstNameController.text, lastName: lastNameController.text, @@ -244,7 +246,7 @@ class _GeneralInfoScreenState extends State { lang: languageController.text, ), ); - await widget.settingsEntity.settingsCubit.updateProfileSettings( + final settingsSaved = await widget.settingsEntity.settingsCubit.updateProfileSettings( profileSettingsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileSettings.copyWith( isPublicProfile: isPublicProfile.value, ), @@ -253,6 +255,10 @@ class _GeneralInfoScreenState extends State { setState(() { isLoading = false; }); + if (detailsSaved && settingsSaved) { + showSuccessToast(S.of(context).data_saved_successfully); + context.pop(); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/lib/features/settings/presentation/pages/other_info_screen.dart b/lib/features/settings/presentation/pages/other_info_screen.dart index 588b6e50..b799cc63 100644 --- a/lib/features/settings/presentation/pages/other_info_screen.dart +++ b/lib/features/settings/presentation/pages/other_info_screen.dart @@ -2,6 +2,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; @@ -137,8 +138,8 @@ class _OtherInfoScreenState extends State { InkWell _saveButton() { return InkWell( - onTap: () { - widget.settingsEntity.settingsCubit.updateProfileDetails( + onTap: () async { + final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( aboutAlergy: aboutAllergyController.text, aboutTakingPils: aboutTakingPillsController.text, @@ -148,7 +149,11 @@ class _OtherInfoScreenState extends State { additionalInfo: additionalInfoController.text, ), ); - GoRouter.of(context).pop(); + if (!mounted) return; + if (saved) { + showSuccessToast(S.of(context).data_saved_successfully); + GoRouter.of(context).pop(); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/lib/features/settings/presentation/pages/physical_activity_screen.dart b/lib/features/settings/presentation/pages/physical_activity_screen.dart index 86b66dd0..aae40880 100644 --- a/lib/features/settings/presentation/pages/physical_activity_screen.dart +++ b/lib/features/settings/presentation/pages/physical_activity_screen.dart @@ -2,6 +2,8 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; +import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; @@ -200,7 +202,7 @@ class _PhysicalActivityScreenState extends State { InkWell _saveButton() { return InkWell( - onTap: () { + onTap: () async { late final double activityCoefficient; switch (_physicalActivity) { case PhysicalActivity.minimum: @@ -221,12 +223,16 @@ class _PhysicalActivityScreenState extends State { default: break; } - widget.settingsEntity.settingsCubit.updateProfileDetails( + final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( activityCoefficient: activityCoefficient, ), ); - GoRouter.of(context).pop(); + if (!mounted) return; + if (saved) { + showSuccessToast(S.of(context).data_saved_successfully); + GoRouter.of(context).pop(); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/lib/features/settings/presentation/pages/physical_form_screen.dart b/lib/features/settings/presentation/pages/physical_form_screen.dart index a7c612b9..3ced30af 100644 --- a/lib/features/settings/presentation/pages/physical_form_screen.dart +++ b/lib/features/settings/presentation/pages/physical_form_screen.dart @@ -2,6 +2,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; @@ -108,8 +109,8 @@ class _PhysicalFormScreenState extends State { InkWell _saveButton() { return InkWell( - onTap: () { - widget.settingsEntity.settingsCubit.updateProfileDetails( + onTap: () async { + final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( chestCircumference: int.parse(chestCircumferenceController.text), waistCircumference: int.parse(waistCircumferenceController.text), @@ -118,7 +119,11 @@ class _PhysicalFormScreenState extends State { weight: double.parse(weightController.text), ), ); - GoRouter.of(context).pop(); + if (!mounted) return; + if (saved) { + showSuccessToast(S.of(context).data_saved_successfully); + GoRouter.of(context).pop(); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/lib/features/settings/presentation/pages/pressure_screen.dart b/lib/features/settings/presentation/pages/pressure_screen.dart index 9f82b216..cf91b298 100644 --- a/lib/features/settings/presentation/pages/pressure_screen.dart +++ b/lib/features/settings/presentation/pages/pressure_screen.dart @@ -4,6 +4,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; @@ -114,8 +115,8 @@ class _PressureScreenState extends State { InkWell _saveButton() { return InkWell( - onTap: () { - widget.settingsEntity.settingsCubit.updateProfileDetails( + onTap: () async { + final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( bloodPressureUp: int.parse(bloodPressureUpController.text), bloodPressureDown: int.parse(bloodPressureDownController.text), @@ -123,7 +124,11 @@ class _PressureScreenState extends State { hasHypo: hypo.value, ), ); - GoRouter.of(context).pop(); + if (!mounted) return; + if (saved) { + showSuccessToast(S.of(context).data_saved_successfully); + GoRouter.of(context).pop(); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart b/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart index 1ec87312..e0092b7d 100644 --- a/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart +++ b/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart @@ -61,6 +61,9 @@ class _VideoCallRecordingsViewState extends State<_VideoCallRecordingsView> { return; } final position = _scrollController.position; + if (position.maxScrollExtent <= 0 || position.pixels < 0) { + return; + } if (position.pixels >= position.maxScrollExtent - 200) { context.read().loadNextPage(); } @@ -170,14 +173,29 @@ class _VideoCallRecordingsViewState extends State<_VideoCallRecordingsView> { } if (state.recordings.isEmpty) { - return Center( - child: Padding( - padding: const EdgeInsets.all(24), - child: Text( - s.video_call_recordings_empty, - textAlign: TextAlign.center, - style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400), - ), + return RefreshIndicator( + onRefresh: () => context.read().load(refresh: true), + child: LayoutBuilder( + builder: (context, constraints) { + return ListView( + physics: const AlwaysScrollableScrollPhysics(), + children: [ + ConstrainedBox( + constraints: BoxConstraints(minHeight: constraints.maxHeight), + child: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + s.video_call_recordings_empty, + textAlign: TextAlign.center, + style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400), + ), + ), + ), + ), + ], + ); + }, ), ); } @@ -186,6 +204,7 @@ class _VideoCallRecordingsViewState extends State<_VideoCallRecordingsView> { onRefresh: () => context.read().load(refresh: true), child: ListView.separated( controller: _scrollController, + physics: const AlwaysScrollableScrollPhysics(), padding: const EdgeInsets.fromLTRB(16, 0, 16, 24), itemCount: state.recordings.length + (state.isLoadingMore ? 1 : 0), separatorBuilder: (_, _) => const SizedBox(height: 16), diff --git a/lib/features/video_calls/recordings/services/public_downloads_saver.dart b/lib/features/video_calls/recordings/services/public_downloads_saver.dart index d0cda3ed..437bda61 100644 --- a/lib/features/video_calls/recordings/services/public_downloads_saver.dart +++ b/lib/features/video_calls/recordings/services/public_downloads_saver.dart @@ -8,7 +8,7 @@ class PublicDownloadsSaver { const PublicDownloadsSaver(); /// Имя папки приложения в Загрузках / Files. - static const appFolderName = 'Itvio'; + static const appFolderName = 'Eatvio'; Future saveToDownloads({ required String sourcePath, diff --git a/lib/features/video_calls/recordings/services/video_call_recording_file_service.dart b/lib/features/video_calls/recordings/services/video_call_recording_file_service.dart index 8bc1c751..0c680fd3 100644 --- a/lib/features/video_calls/recordings/services/video_call_recording_file_service.dart +++ b/lib/features/video_calls/recordings/services/video_call_recording_file_service.dart @@ -19,7 +19,7 @@ class VideoCallRecordingFileService { final Dio dio; final PublicDownloadsSaver downloadsSaver; - /// Скачивает запись и сохраняет в `Загрузки/Itvio` (Android) + /// Скачивает запись и сохраняет в `Загрузки/Eatvio` (Android) /// или Documents приложения (iOS, видно в Files). Future downloadRecordingFile({ required String fileUrl, diff --git a/lib/generated/intl/messages_en.dart b/lib/generated/intl/messages_en.dart index d54c3c65..cf92982e 100644 --- a/lib/generated/intl/messages_en.dart +++ b/lib/generated/intl/messages_en.dart @@ -354,6 +354,9 @@ class MessageLookup extends MessageLookupByLibrary { "customer_price": MessageLookupByLibrary.simpleMessage( "Цена для покупателя", ), + "data_saved_successfully": MessageLookupByLibrary.simpleMessage( + "Data saved successfully", + ), "date_has_ben_set": MessageLookupByLibrary.simpleMessage( "Дата старта начала консультации установлена", ), @@ -1201,7 +1204,7 @@ class MessageLookup extends MessageLookupByLibrary { ), "video_call_recordings_download_success": MessageLookupByLibrary.simpleMessage( - "Recording saved to Downloads/Itvio", + "Recording saved to Downloads/Eatvio", ), "video_call_recordings_download_success_ios": MessageLookupByLibrary.simpleMessage( diff --git a/lib/generated/intl/messages_ru.dart b/lib/generated/intl/messages_ru.dart index cd2d772c..4e002259 100644 --- a/lib/generated/intl/messages_ru.dart +++ b/lib/generated/intl/messages_ru.dart @@ -165,6 +165,9 @@ class MessageLookup extends MessageLookupByLibrary { "customer_price": MessageLookupByLibrary.simpleMessage( "Цена для покупателя", ), + "data_saved_successfully": MessageLookupByLibrary.simpleMessage( + "Данные успешно сохранены", + ), "date_of_birth": MessageLookupByLibrary.simpleMessage("Дата рождения"), "day": MessageLookupByLibrary.simpleMessage("День"), "days": MessageLookupByLibrary.simpleMessage("дней"), @@ -696,7 +699,7 @@ class MessageLookup extends MessageLookupByLibrary { ), "video_call_recordings_download_success": MessageLookupByLibrary.simpleMessage( - "Запись сохранена в Загрузки/Itvio", + "Запись сохранена в Загрузки/Eatvio", ), "video_call_recordings_download_success_ios": MessageLookupByLibrary.simpleMessage( diff --git a/lib/generated/l10n.dart b/lib/generated/l10n.dart index fcafdb73..d1e2ce1e 100644 --- a/lib/generated/l10n.dart +++ b/lib/generated/l10n.dart @@ -134,6 +134,16 @@ class S { ); } + /// `Data saved successfully` + String get data_saved_successfully { + return Intl.message( + 'Data saved successfully', + name: 'data_saved_successfully', + desc: '', + args: [], + ); + } + /// `Страна` String get country { return Intl.message('Страна', name: 'country', desc: '', args: []); @@ -5432,10 +5442,10 @@ class S { ); } - /// `Recording saved to Downloads/Itvio` + /// `Recording saved to Downloads/Eatvio` String get video_call_recordings_download_success { return Intl.message( - 'Recording saved to Downloads/Itvio', + 'Recording saved to Downloads/Eatvio', name: 'video_call_recordings_download_success', desc: '', args: [], diff --git a/lib/l10n/intl_en.arb b/lib/l10n/intl_en.arb index f7da7936..b80fd4e3 100644 --- a/lib/l10n/intl_en.arb +++ b/lib/l10n/intl_en.arb @@ -9,6 +9,7 @@ "last_name": "Фамилия", "what_is_your_name": "Как вас зовут?", "date_of_birth": "Дата рождения", + "data_saved_successfully": "Data saved successfully", "country": "Страна", "Russia": "Россия", "city": "Город", @@ -829,7 +830,7 @@ } }, "video_call_recordings_download_error": "Could not download the recording. Please try again later.", - "video_call_recordings_download_success": "Recording saved to Downloads/Itvio", + "video_call_recordings_download_success": "Recording saved to Downloads/Eatvio", "video_call_recordings_download_success_ios": "Recording saved to the Files app", "video_call_recordings_player_error": "Could not play the recording", "video_call_recordings_card_title": "Video consultation with a nutrition specialist", diff --git a/lib/l10n/intl_ru.arb b/lib/l10n/intl_ru.arb index b46e31e9..e9db3992 100644 --- a/lib/l10n/intl_ru.arb +++ b/lib/l10n/intl_ru.arb @@ -9,6 +9,7 @@ "last_name": "Фамилия", "what_is_your_name": "Как вас зовут?", "date_of_birth": "Дата рождения", + "data_saved_successfully": "Данные успешно сохранены", "country": "Страна", "Russia": "Россия", "city": "Город", @@ -584,7 +585,7 @@ } }, "video_call_recordings_download_error": "Не удалось скачать запись. Попробуйте позже.", - "video_call_recordings_download_success": "Запись сохранена в Загрузки/Itvio", + "video_call_recordings_download_success": "Запись сохранена в Загрузки/Eatvio", "video_call_recordings_download_success_ios": "Запись сохранена в приложении «Файлы»", "video_call_recordings_player_error": "Не удалось воспроизвести запись", "video_call_recordings_card_title": "Видеоконсультация со специалистом по питанию", diff --git a/pubspec.yaml b/pubspec.yaml index dad171d6..3f5a8ec7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: eatvio_app description: A new Flutter project. -version: 1.3.72+161 +version: 1.3.74+163 publish_to: 'none' environment: diff --git a/test/core/widgets/custom_popup_test.dart b/test/core/widgets/custom_popup_test.dart index 18506e8d..5044255d 100644 --- a/test/core/widgets/custom_popup_test.dart +++ b/test/core/widgets/custom_popup_test.dart @@ -86,6 +86,7 @@ void main() { ), ); + await tester.pump(); await tester.tap(find.byIcon(Icons.more_horiz_rounded)); await tester.pumpAndSettle(); @@ -108,6 +109,7 @@ void main() { ), ); + await tester.pump(); await tester.tap(find.byIcon(Icons.more_horiz_rounded)); await tester.pumpAndSettle(); @@ -131,6 +133,7 @@ void main() { ), ); + await tester.pump(); await tester.tap(find.byIcon(Icons.more_horiz_rounded)); await tester.pumpAndSettle(); @@ -153,6 +156,7 @@ void main() { ), ); + await tester.pump(); await tester.tap(find.byIcon(Icons.more_horiz_rounded)); await tester.pumpAndSettle(); @@ -175,6 +179,7 @@ void main() { ), ); + await tester.pump(); await tester.tap(find.byIcon(Icons.more_horiz_rounded)); await tester.pumpAndSettle(); @@ -196,6 +201,7 @@ void main() { ), ); + await tester.pump(); await tester.tap(find.byIcon(Icons.more_horiz_rounded)); await tester.pumpAndSettle(); @@ -217,6 +223,7 @@ void main() { ), ); + await tester.pump(); await tester.tap(find.byIcon(Icons.more_horiz_rounded)); await tester.pumpAndSettle(); @@ -237,6 +244,7 @@ void main() { ), ); + await tester.pump(); await tester.tap(find.byIcon(Icons.more_horiz_rounded)); await tester.pumpAndSettle(); @@ -257,6 +265,7 @@ void main() { ), ); + await tester.pump(); await tester.tap(find.byIcon(Icons.more_horiz_rounded)); await tester.pumpAndSettle(); diff --git a/test/features/chat/presentation/pages/chat_screen_loaded_smoke_test.dart b/test/features/chat/presentation/pages/chat_screen_loaded_smoke_test.dart index 65fe4167..4075bdfe 100644 --- a/test/features/chat/presentation/pages/chat_screen_loaded_smoke_test.dart +++ b/test/features/chat/presentation/pages/chat_screen_loaded_smoke_test.dart @@ -12,6 +12,12 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_ import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_state.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_screen.dart'; +import 'package:eatvio_app/features/chat/presentation/widgets/video_call_chat_message_widget.dart'; +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; +import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; +import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart'; +import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -55,13 +61,57 @@ void main() { final fakeBundle = _FakeAssetBundle({ 'assets/icons/error_icon.svg': fakeSvg, + 'assets/icons/video_call/vc_control_enter.svg': fakeSvg, }); + const plan = PlanModel( + id: 1, + slug: 'test-plan', + name: 'Test Plan', + image: 'https://example.com/image.jpg', + duration: 30, + state: 'active', + type: PlanType(fit: true, slim: false, behavior: false, wellness: false), + details: 'Test details', + packetsCount: 3, + author: Author( + authorSlug: 'author', + authorName: 'Author Name', + authorProfileIcon: 'https://example.com/icon.jpg', + authorIsMe: false, + ), + totalLikes: 10, + totalViews: 100, + totalComments: 5, + isFavorite: false, + minPriceOfOptions: 1000, + maxPriceOfOptions: 2000, + wasLikedByMe: false, + ); + + ChosenPlanModel chosenPlan(ChosenPlanStateEnum state) { + return ChosenPlanModel( + id: 7, + optionType: 'options1', + startDate: DateTime(2025, 1, 1), + chosenPlanState: state, + chatId: '1', + consultantId: 2, + plan: plan, + ); + } + Widget wrap(Widget child, ChatsCubit chatsCubit) { return DefaultAssetBundle( bundle: fakeBundle, child: MaterialApp( theme: ThemeHelper().themeData(), + locale: const Locale('ru'), + localizationsDelegates: const [ + S.delegate, + ...GlobalMaterialLocalizations.delegates, + ], + supportedLocales: S.delegate.supportedLocales, home: BlocProvider.value(value: chatsCubit, child: child), ), ); @@ -214,9 +264,133 @@ void main() { expect(find.text('sending...'), findsOneWidget); expect(find.text('tap to retry'), findsOneWidget); expect(find.text('file.pdf'), findsOneWidget); + expect(find.byIcon(Icons.videocam_rounded), findsNothing); VisibilityDetectorController.instance.notifyNow(); await tester.pump(); }); + + Future pumpLoadedChat( + WidgetTester tester, { + ChosenPlanModel? plan, + List messages = const [], + }) async { + final chatRoomCubit = MockChatRoomCubit(); + final chatsCubit = MockChatsCubit(); + const chatRoom = ChatRoomModel( + id: '1', + chatRoomSettings: ChatRoomSettingsModel(name: 'room', state: 'active'), + users: Users( + sender: ChatUserModel( + id: 1, + name: 'Me', + slug: 'me', + profilePhotoUrl: null, + ), + receiver: ChatUserModel( + id: 2, + name: 'User Two', + slug: 'user-two', + profilePhotoUrl: null, + ), + ), + chosenPlanId: 7, + chosenPlan: null, + ); + final state = ChatRoomState.loaded( + chatRoom: chatRoom.copyWith(chosenPlan: plan), + chatMessages: messages, + hasCard: false, + isTyping: false, + isLoading: false, + ); + + when(chatRoomCubit.state).thenReturn(state); + when( + chatRoomCubit.stream, + ).thenAnswer((_) => const Stream.empty()); + when(chatRoomCubit.close()).thenAnswer((_) async => Future.value()); + when( + chatRoomCubit.initChat( + any, + sendInitialMessage: anyNamed('sendInitialMessage'), + orderId: anyNamed('orderId'), + ), + ).thenAnswer((_) async => 'uuid'); + when(chatRoomCubit.setTimer()).thenReturn(null); + when(chatRoomCubit.refreshChat()).thenAnswer((_) async {}); + + if (sl.isRegistered()) { + sl.unregister(); + } + sl.registerFactory(() => chatRoomCubit); + + when(chatsCubit.state).thenReturn(ChatsState()); + when(chatsCubit.stream).thenAnswer((_) => const Stream.empty()); + when(chatsCubit.close()).thenAnswer((_) async => Future.value()); + + await tester.pumpWidget( + wrap( + const ChatScreen(uuid: 'uuid', sendInitialMessage: false), + chatsCubit, + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + } + + ChatMessageModel incomingCallMessage() { + return ChatMessageModel( + id: 9, + data: 'Видеозвонок', + mediaData: const [], + authorId: 2, + updatedAt: DateTime(2025, 1, 2, 11), + isRead: true, + isCurrentUserAuthor: false, + roomId: '1', + type: ChatMessageType.videoCallStarted, + messageState: MessageState.sent, + uuid: 'call', + ); + } + + testWidgets('shows the call button for an active consultation', ( + tester, + ) async { + await pumpLoadedChat( + tester, + plan: chosenPlan(ChosenPlanStateEnum.stateInProgress), + messages: [incomingCallMessage()], + ); + + expect(find.byIcon(Icons.videocam_rounded), findsOneWidget); + expect(find.byType(VideoCallChatMessageWidget), findsOneWidget); + }); + + testWidgets('hides the call button for a finished consultation', ( + tester, + ) async { + await pumpLoadedChat( + tester, + plan: chosenPlan(ChosenPlanStateEnum.stateDone), + messages: [incomingCallMessage()], + ); + + expect(find.byIcon(Icons.videocam_rounded), findsNothing); + expect(find.byType(VideoCallChatMessageWidget), findsNothing); + expect(find.text('Видеозвонок'), findsOneWidget); + }); + + testWidgets('hides the call button for a canceled consultation', ( + tester, + ) async { + await pumpLoadedChat( + tester, + plan: chosenPlan(ChosenPlanStateEnum.stateCanceledByTheInitiator), + ); + + expect(find.byIcon(Icons.videocam_rounded), findsNothing); + }); }); } diff --git a/test/features/chat/presentation/widgets/chat_consultation_header_test.dart b/test/features/chat/presentation/widgets/chat_consultation_header_test.dart index e984ef15..e96d26eb 100644 --- a/test/features/chat/presentation/widgets/chat_consultation_header_test.dart +++ b/test/features/chat/presentation/widgets/chat_consultation_header_test.dart @@ -18,6 +18,11 @@ Widget _wrap(Widget child) { ); } +Future _pump(WidgetTester tester, Widget child) async { + await tester.pumpWidget(_wrap(child)); + await tester.pump(); +} + void main() { group('ChatConsultationHeader', () { testWidgets('вызывает onInfoTap по тапу на info', (tester) async { @@ -27,13 +32,12 @@ void main() { hasPersonalDiet: false, ); - await tester.pumpWidget( - _wrap( - ChatConsultationHeader( - progress: progress, - showInfoButton: true, - onInfoTap: () => tapped++, - ), + await _pump( + tester, + ChatConsultationHeader( + progress: progress, + showInfoButton: true, + onInfoTap: () => tapped++, ), ); @@ -54,13 +58,12 @@ void main() { expect(progress.showProgressPlank, isTrue); expect(progress.dietStatus, PersonalDietStatus.proposed); - await tester.pumpWidget( - _wrap( - ChatConsultationHeader( - progress: progress, - showInfoButton: false, - onInfoTap: () {}, - ), + await _pump( + tester, + ChatConsultationHeader( + progress: progress, + showInfoButton: false, + onInfoTap: () {}, ), ); diff --git a/test/features/consultations/presentation/widgets/consultation_progress_plank_test.dart b/test/features/consultations/presentation/widgets/consultation_progress_plank_test.dart index 364a1dc0..dc94ec4f 100644 --- a/test/features/consultations/presentation/widgets/consultation_progress_plank_test.dart +++ b/test/features/consultations/presentation/widgets/consultation_progress_plank_test.dart @@ -15,6 +15,11 @@ Widget _wrap(Widget child) { ); } +Future _pump(WidgetTester tester, Widget child) async { + await tester.pumpWidget(_wrap(child)); + await tester.pump(); +} + void main() { group('ConsultationProgressPlank', () { testWidgets('не строит шаги при showProgressPlank=false', (tester) async { @@ -24,9 +29,7 @@ void main() { ); expect(progress.showProgressPlank, isFalse); - await tester.pumpWidget( - _wrap(ConsultationProgressPlank(progress: progress)), - ); + await _pump(tester, ConsultationProgressPlank(progress: progress)); expect( find.descendant( @@ -48,9 +51,7 @@ void main() { ); expect(progress.showProgressPlank, isTrue); - await tester.pumpWidget( - _wrap(ConsultationProgressPlank(progress: progress)), - ); + await _pump(tester, ConsultationProgressPlank(progress: progress)); final s = S.of(tester.element(find.byType(ConsultationProgressPlank))); @@ -70,12 +71,11 @@ void main() { hasPersonalDiet: false, ); - await tester.pumpWidget( - _wrap( - SizedBox( - width: 360, - child: ConsultationProgressPlank(progress: progress), - ), + await _pump( + tester, + SizedBox( + width: 360, + child: ConsultationProgressPlank(progress: progress), ), ); diff --git a/test/features/consultations/presentation/widgets/personal_diet_status_chip_test.dart b/test/features/consultations/presentation/widgets/personal_diet_status_chip_test.dart index 50786729..73d5e99f 100644 --- a/test/features/consultations/presentation/widgets/personal_diet_status_chip_test.dart +++ b/test/features/consultations/presentation/widgets/personal_diet_status_chip_test.dart @@ -15,6 +15,11 @@ Widget _wrap(Widget child) { ); } +Future _pump(WidgetTester tester, Widget child) async { + await tester.pumpWidget(_wrap(child)); + await tester.pump(); +} + Widget _chip( ChosenPlanStateEnum state, { bool hasPersonalDiet = true, @@ -32,9 +37,7 @@ Widget _chip( void main() { group('PersonalDietStatusChip', () { testWidgets('notRequired + active ничего не показывает', (tester) async { - await tester.pumpWidget( - _wrap(_chip(ChosenPlanStateEnum.stateInited, hasPersonalDiet: false)), - ); + await _pump(tester, _chip(ChosenPlanStateEnum.stateInited, hasPersonalDiet: false)); expect( find.descendant( @@ -47,7 +50,7 @@ void main() { }); testWidgets('proposed показывает personal_diet_proposed', (tester) async { - await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.stateStarted))); + await _pump(tester, _chip(ChosenPlanStateEnum.stateStarted)); final s = S.of(tester.element(find.byType(PersonalDietStatusChip))); @@ -55,12 +58,11 @@ void main() { }); testWidgets('proposed с названием показывает имя диеты', (tester) async { - await tester.pumpWidget( - _wrap( - _chip( - ChosenPlanStateEnum.stateStarted, - personalDietName: 'Индивидуальный план питания', - ), + await _pump( + tester, + _chip( + ChosenPlanStateEnum.stateStarted, + personalDietName: 'Индивидуальный план питания', ), ); @@ -75,7 +77,7 @@ void main() { testWidgets('notProposed показывает personal_diet_not_proposed', ( tester, ) async { - await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.statePaid))); + await _pump(tester, _chip(ChosenPlanStateEnum.statePaid)); final s = S.of(tester.element(find.byType(PersonalDietStatusChip))); @@ -83,9 +85,7 @@ void main() { }); testWidgets('canceled показывает orderCanceled', (tester) async { - await tester.pumpWidget( - _wrap(_chip(ChosenPlanStateEnum.stateCanceledByTheInitiator)), - ); + await _pump(tester, _chip(ChosenPlanStateEnum.stateCanceledByTheInitiator)); final s = S.of(tester.element(find.byType(PersonalDietStatusChip))); @@ -93,9 +93,7 @@ void main() { }); testWidgets('paymentFailed показывает payment_failed', (tester) async { - await tester.pumpWidget( - _wrap(_chip(ChosenPlanStateEnum.statePaymentFailed)), - ); + await _pump(tester, _chip(ChosenPlanStateEnum.statePaymentFailed)); final s = S.of(tester.element(find.byType(PersonalDietStatusChip))); diff --git a/test/features/diary/presentation/bloc/diary_cubit_test.dart b/test/features/diary/presentation/bloc/diary_cubit_test.dart index 4f593dfd..4acb25de 100644 --- a/test/features/diary/presentation/bloc/diary_cubit_test.dart +++ b/test/features/diary/presentation/bloc/diary_cubit_test.dart @@ -1,5 +1,8 @@ +import 'dart:async'; + import 'package:dio/dio.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/features/consultations/models/consultation_model.dart'; import 'package:eatvio_app/features/diary/entities/diary_future_diet_day_entity.dart'; import 'package:eatvio_app/features/diary/models/diary_day_model.dart'; import 'package:eatvio_app/features/diary/models/nutrition_model.dart'; @@ -41,7 +44,11 @@ void main() { date: '2024-01-15', closed: 0, comment: '', - typeOfDiary: TypeOfDiaryModel(hasChosenDiet: false, hasChosenPlan: false, diaryState: null), + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: false, + hasChosenPlan: false, + diaryState: null, + ), meals: [], chosenPlanId: null, dayOfChosenDiet: null, @@ -49,8 +56,18 @@ void main() { ); const testNutrition = NutritionDataModel( - dailyNutritionIntake: NutritionModel(energy: 2000.0, proteins: 150.0, fats: 80.0, carbohydrates: 250.0), - dailyNutritionRecommendation: NutritionModel(energy: 2200.0, proteins: 160.0, fats: 90.0, carbohydrates: 270.0), + dailyNutritionIntake: NutritionModel( + energy: 2000.0, + proteins: 150.0, + fats: 80.0, + carbohydrates: 250.0, + ), + dailyNutritionRecommendation: NutritionModel( + energy: 2200.0, + proteins: 160.0, + fats: 90.0, + carbohydrates: 270.0, + ), ); setUp(() { @@ -91,9 +108,15 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenAnswer((_) async => Future.value()); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -120,8 +143,12 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.getDiaryDay(any)).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDay(any), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -132,7 +159,10 @@ void main() { ), ); - final result = await diaryCubit!.fetchDiaryV2(needLoading: true, diaryId: 1); + final result = await diaryCubit!.fetchDiaryV2( + needLoading: true, + diaryId: 1, + ); expect(result, true); await Future.delayed(const Duration(milliseconds: 100)); @@ -143,11 +173,18 @@ void main() { when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenThrow( DioException( requestOptions: RequestOptions(path: ''), - response: Response(requestOptions: RequestOptions(path: ''), statusCode: 422), + response: Response( + requestOptions: RequestOptions(path: ''), + statusCode: 422, + ), ), ); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -182,9 +219,15 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenAnswer((_) async => Future.value()); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -203,75 +246,100 @@ void main() { expect(diaryCubit!.state, isA()); }); - test('setDiaryForDietOnly - устанавливает дневник только для диеты', () async { - diaryCubit = DiaryCubit( - diaryRepository: mockDiaryRepository, - glossaryRepository: mockGlossaryRepository, - profileRepository: mockProfileRepository, - dietRepository: mockDietRepository, - chatRepository: mockChatRepository, - settingsRepository: mockSettingsRepository, - ); - const diet = Diet( - id: 1, - slug: 'test-diet', - name: 'Test Diet', - image: '', - duration: 7, - state: DietState.active, - type: DietType(), - details: '', - dailySchedule: { - 1: { - 1: {1: DailySchedule(name: 'Яблоко', portion: Portion.grams, quantity: 1)}, + test( + 'setDiaryForDietOnly - устанавливает дневник только для диеты', + () async { + diaryCubit = DiaryCubit( + diaryRepository: mockDiaryRepository, + glossaryRepository: mockGlossaryRepository, + profileRepository: mockProfileRepository, + dietRepository: mockDietRepository, + chatRepository: mockChatRepository, + settingsRepository: mockSettingsRepository, + ); + const diet = Diet( + id: 1, + slug: 'test-diet', + name: 'Test Diet', + image: '', + duration: 7, + state: DietState.active, + type: DietType(), + details: '', + dailySchedule: { + 1: { + 1: { + 1: DailySchedule( + name: 'Яблоко', + portion: Portion.grams, + quantity: 1, + ), + }, + }, }, - }, - author: Author(authorSlug: 'test', authorName: 'Test', authorProfileIcon: '', authorIsMe: false), - totalLikes: 0, - totalViews: 0, - totalComments: 0, - wasLikedByMe: false, - isFavorite: false, - dailyNutrition: [], - ); + author: Author( + authorSlug: 'test', + authorName: 'Test', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + wasLikedByMe: false, + isFavorite: false, + dailyNutrition: [], + ); - when(mockDietRepository.getDiet(1)).thenAnswer((_) async => diet); + when(mockDietRepository.getDiet(1)).thenAnswer((_) async => diet); - final result = await diaryCubit!.setDiaryForDietOnly( - const DiaryFutureDietDayEntity( - date: '2024-01-15', - typeOfDiary: TypeOfDiaryModel(hasChosenDiet: true, hasChosenPlan: false, diaryState: null), - meals: [], - dayOfChosenDiet: 1, - diet: DiaryDietModel(id: 1, duration: 7, name: 'Test Diet'), - ), - ); + final result = await diaryCubit!.setDiaryForDietOnly( + const DiaryFutureDietDayEntity( + date: '2024-01-15', + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: true, + hasChosenPlan: false, + diaryState: null, + ), + meals: [], + dayOfChosenDiet: 1, + diet: DiaryDietModel(id: 1, duration: 7, name: 'Test Diet'), + ), + ); - expect(result, true); - expect(diaryCubit!.state, isA()); - }); + expect(result, true); + expect(diaryCubit!.state, isA()); + }, + ); - test('setDiaryForDietOnly - возвращает false если нет выбранной диеты', () async { - diaryCubit = DiaryCubit( - diaryRepository: mockDiaryRepository, - glossaryRepository: mockGlossaryRepository, - profileRepository: mockProfileRepository, - dietRepository: mockDietRepository, - chatRepository: mockChatRepository, - settingsRepository: mockSettingsRepository, - ); - final result = await diaryCubit!.setDiaryForDietOnly( - const DiaryFutureDietDayEntity( - date: '2024-01-15', - typeOfDiary: TypeOfDiaryModel(hasChosenDiet: false, hasChosenPlan: false, diaryState: null), - meals: [], - dayOfChosenDiet: null, - diet: null, - ), - ); + test( + 'setDiaryForDietOnly - возвращает false если нет выбранной диеты', + () async { + diaryCubit = DiaryCubit( + diaryRepository: mockDiaryRepository, + glossaryRepository: mockGlossaryRepository, + profileRepository: mockProfileRepository, + dietRepository: mockDietRepository, + chatRepository: mockChatRepository, + settingsRepository: mockSettingsRepository, + ); + final result = await diaryCubit!.setDiaryForDietOnly( + const DiaryFutureDietDayEntity( + date: '2024-01-15', + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: false, + hasChosenPlan: false, + diaryState: null, + ), + meals: [], + dayOfChosenDiet: null, + diet: null, + ), + ); - expect(result, false); - }); + expect(result, false); + }, + ); test('finishDiaryDay - завершает день дневника', () async { diaryCubit = DiaryCubit( @@ -283,10 +351,19 @@ void main() { settingsRepository: mockSettingsRepository, ); when( - mockDiaryRepository.finishDiaryDay(diaryId: anyNamed('diaryId'), wakeUp: anyNamed('wakeUp'), retire: anyNamed('retire'), comment: anyNamed('comment')), + mockDiaryRepository.finishDiaryDay( + diaryId: anyNamed('diaryId'), + wakeUp: anyNamed('wakeUp'), + retire: anyNamed('retire'), + comment: anyNamed('comment'), + ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -299,7 +376,11 @@ void main() { await diaryCubit!.fetchDiaryV2(needLoading: true); await Future.delayed(const Duration(milliseconds: 100)); - await diaryCubit!.finishDiaryDay(diaryId: 1, wakeUp: '07:00', retire: '23:00'); + await diaryCubit!.finishDiaryDay( + diaryId: 1, + wakeUp: '07:00', + retire: '23:00', + ); await Future.delayed(const Duration(milliseconds: 100)); }); @@ -322,8 +403,12 @@ void main() { productNutritionalValueId: anyNamed('productNutritionalValueId'), ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -336,7 +421,13 @@ void main() { await diaryCubit!.fetchDiaryV2(needLoading: true); await Future.delayed(const Duration(milliseconds: 100)); - await diaryCubit!.addProductToMeal(diaryId: 1, mealId: 1, productName: 'Яблоко', portion: '100г', quantity: 2); + await diaryCubit!.addProductToMeal( + diaryId: 1, + mealId: 1, + productName: 'Яблоко', + portion: '100г', + quantity: 2, + ); await Future.delayed(const Duration(milliseconds: 100)); }); @@ -350,10 +441,18 @@ void main() { settingsRepository: mockSettingsRepository, ); when( - mockDiaryRepository.markEaten(diaryId: anyNamed('diaryId'), mealId: anyNamed('mealId'), portionId: anyNamed('portionId')), + mockDiaryRepository.markEaten( + diaryId: anyNamed('diaryId'), + mealId: anyNamed('mealId'), + portionId: anyNamed('portionId'), + ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -370,39 +469,42 @@ void main() { await Future.delayed(const Duration(milliseconds: 100)); }); - test('getGlossaryListByQuery - получает список глоссариев по запросу', () async { - diaryCubit = DiaryCubit( - diaryRepository: mockDiaryRepository, - glossaryRepository: mockGlossaryRepository, - profileRepository: mockProfileRepository, - dietRepository: mockDietRepository, - chatRepository: mockChatRepository, - settingsRepository: mockSettingsRepository, - ); - when(mockGlossaryRepository.getGlossaryListByQuery(any)).thenAnswer( - (_) async => [ - const GlossaryModel( - id: 1, - name: 'Яблоко', - grInPortion: 100, - energyOn100Gr: 52.0, - proteinsOn100Gr: 0.3, - fatsOn100Gr: 0.2, - carbohydratesOn100Gr: 14.0, - energyOnPortion: 52.0, - proteinsOnPortion: 0.3, - fatsOnPortion: 0.2, - carbohydratesOnPortion: 14.0, - ), - ], - ); + test( + 'getGlossaryListByQuery - получает список глоссариев по запросу', + () async { + diaryCubit = DiaryCubit( + diaryRepository: mockDiaryRepository, + glossaryRepository: mockGlossaryRepository, + profileRepository: mockProfileRepository, + dietRepository: mockDietRepository, + chatRepository: mockChatRepository, + settingsRepository: mockSettingsRepository, + ); + when(mockGlossaryRepository.getGlossaryListByQuery(any)).thenAnswer( + (_) async => [ + const GlossaryModel( + id: 1, + name: 'Яблоко', + grInPortion: 100, + energyOn100Gr: 52.0, + proteinsOn100Gr: 0.3, + fatsOn100Gr: 0.2, + carbohydratesOn100Gr: 14.0, + energyOnPortion: 52.0, + proteinsOnPortion: 0.3, + fatsOnPortion: 0.2, + carbohydratesOnPortion: 14.0, + ), + ], + ); - final result = await diaryCubit!.getGlossaryListByQuery('яблоко'); + final result = await diaryCubit!.getGlossaryListByQuery('яблоко'); - expect(result, isA>()); - expect(result.length, 1); - expect(result.first.name, 'Яблоко'); - }); + expect(result, isA>()); + expect(result.length, 1); + expect(result.first.name, 'Яблоко'); + }, + ); test('fillSatiety - заполняет сытость', () async { diaryCubit = DiaryCubit( @@ -414,10 +516,18 @@ void main() { settingsRepository: mockSettingsRepository, ); when( - mockDiaryRepository.fillSatiety(diaryId: anyNamed('diaryId'), mealId: anyNamed('mealId'), satiety: anyNamed('satiety')), + mockDiaryRepository.fillSatiety( + diaryId: anyNamed('diaryId'), + mealId: anyNamed('mealId'), + satiety: anyNamed('satiety'), + ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -444,10 +554,18 @@ void main() { settingsRepository: mockSettingsRepository, ); when( - mockDiaryRepository.fillMood(diaryId: anyNamed('diaryId'), mealId: anyNamed('mealId'), mood: anyNamed('mood')), + mockDiaryRepository.fillMood( + diaryId: anyNamed('diaryId'), + mealId: anyNamed('mealId'), + mood: anyNamed('mood'), + ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -486,8 +604,12 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -512,7 +634,9 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenThrow(Exception('Ошибка')); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenThrow(Exception('Ошибка')); await diaryCubit!.updateCurrentDiary(); await Future.delayed(const Duration(milliseconds: 100)); @@ -527,7 +651,9 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); final result = await diaryCubit!.getNutrition(1); @@ -556,8 +682,12 @@ void main() { portionState: anyNamed('portionState'), ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -604,10 +734,18 @@ void main() { settingsRepository: mockSettingsRepository, ); when( - mockDiaryRepository.unmarkEaten(diaryId: anyNamed('diaryId'), mealId: anyNamed('mealId'), portionId: anyNamed('portionId')), + mockDiaryRepository.unmarkEaten( + diaryId: anyNamed('diaryId'), + mealId: anyNamed('mealId'), + portionId: anyNamed('portionId'), + ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -622,7 +760,9 @@ void main() { await Future.delayed(const Duration(milliseconds: 100)); await diaryCubit!.unmarkEaten(diaryId: 1, mealId: 1, portionId: 5); await Future.delayed(const Duration(milliseconds: 100)); - verify(mockDiaryRepository.unmarkEaten(diaryId: 1, mealId: 1, portionId: 5)).called(1); + verify( + mockDiaryRepository.unmarkEaten(diaryId: 1, mealId: 1, portionId: 5), + ).called(1); }); test('restore - восстанавливает продукт', () async { @@ -635,10 +775,18 @@ void main() { settingsRepository: mockSettingsRepository, ); when( - mockDiaryRepository.restore(diaryId: anyNamed('diaryId'), mealId: anyNamed('mealId'), portionId: anyNamed('portionId')), + mockDiaryRepository.restore( + diaryId: anyNamed('diaryId'), + mealId: anyNamed('mealId'), + portionId: anyNamed('portionId'), + ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -653,7 +801,9 @@ void main() { await Future.delayed(const Duration(milliseconds: 100)); await diaryCubit!.restore(diaryId: 1, mealId: 1, portionId: 5); await Future.delayed(const Duration(milliseconds: 100)); - verify(mockDiaryRepository.restore(diaryId: 1, mealId: 1, portionId: 5)).called(1); + verify( + mockDiaryRepository.restore(diaryId: 1, mealId: 1, portionId: 5), + ).called(1); }); test('deleteProductFromMeal - удаляет продукт из приема пищи', () async { @@ -666,10 +816,18 @@ void main() { settingsRepository: mockSettingsRepository, ); when( - mockDiaryRepository.deleteProductFromMeal(diaryId: anyNamed('diaryId'), mealId: anyNamed('mealId'), portionId: anyNamed('portionId')), + mockDiaryRepository.deleteProductFromMeal( + diaryId: anyNamed('diaryId'), + mealId: anyNamed('mealId'), + portionId: anyNamed('portionId'), + ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -682,9 +840,19 @@ void main() { await diaryCubit!.fetchDiaryV2(needLoading: true); await Future.delayed(const Duration(milliseconds: 100)); - await diaryCubit!.deleteProductFromMeal(diaryId: 1, mealId: 1, portionId: 5); + await diaryCubit!.deleteProductFromMeal( + diaryId: 1, + mealId: 1, + portionId: 5, + ); await Future.delayed(const Duration(milliseconds: 100)); - verify(mockDiaryRepository.deleteProductFromMeal(diaryId: 1, mealId: 1, portionId: 5)).called(1); + verify( + mockDiaryRepository.deleteProductFromMeal( + diaryId: 1, + mealId: 1, + portionId: 5, + ), + ).called(1); }); test('sendProductToModeration - отправляет продукт на модерацию', () async { @@ -721,10 +889,24 @@ void main() { ), ).thenAnswer((_) async => moderationModel); - final result = await diaryCubit!.sendProductToModeration(name: 'Новый продукт', energy: 100.0, proteins: 10.0, fats: 5.0, carbohydrates: 15.0); + final result = await diaryCubit!.sendProductToModeration( + name: 'Новый продукт', + energy: 100.0, + proteins: 10.0, + fats: 5.0, + carbohydrates: 15.0, + ); expect(result, moderationModel); - verify(mockDiaryRepository.sendProductToModeration(name: 'Новый продукт', energy: 100.0, proteins: 10.0, fats: 5.0, carbohydrates: 15.0)).called(1); + verify( + mockDiaryRepository.sendProductToModeration( + name: 'Новый продукт', + energy: 100.0, + proteins: 10.0, + fats: 5.0, + carbohydrates: 15.0, + ), + ).called(1); }); test('sendProductToModeration - возвращает null при ошибке', () async { @@ -746,7 +928,13 @@ void main() { ), ).thenThrow(Exception('Ошибка')); - final result = await diaryCubit!.sendProductToModeration(name: 'Новый продукт', energy: 100.0, proteins: 10.0, fats: 5.0, carbohydrates: 15.0); + final result = await diaryCubit!.sendProductToModeration( + name: 'Новый продукт', + energy: 100.0, + proteins: 10.0, + fats: 5.0, + carbohydrates: 15.0, + ); expect(result, isNull); }); @@ -761,10 +949,18 @@ void main() { settingsRepository: mockSettingsRepository, ); when( - mockDiaryRepository.fillTime(diaryId: anyNamed('diaryId'), mealId: anyNamed('mealId'), time: anyNamed('time')), + mockDiaryRepository.fillTime( + diaryId: anyNamed('diaryId'), + mealId: anyNamed('mealId'), + time: anyNamed('time'), + ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -779,7 +975,9 @@ void main() { await Future.delayed(const Duration(milliseconds: 100)); await diaryCubit!.fillTime(diaryId: 1, time: '12:00'); await Future.delayed(const Duration(milliseconds: 100)); - verify(mockDiaryRepository.fillTime(diaryId: 1, mealId: 1, time: '12:00')).called(1); + verify( + mockDiaryRepository.fillTime(diaryId: 1, mealId: 1, time: '12:00'), + ).called(1); }); test('fillWakeup - заполняет время пробуждения', () async { @@ -791,9 +989,18 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.fillWakeup(diaryId: anyNamed('diaryId'), time: anyNamed('time'))).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.fillWakeup( + diaryId: anyNamed('diaryId'), + time: anyNamed('time'), + ), + ).thenAnswer((_) async => Future.value()); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -808,7 +1015,9 @@ void main() { await Future.delayed(const Duration(milliseconds: 100)); await diaryCubit!.fillWakeup(diaryId: 1, time: '07:00'); await Future.delayed(const Duration(milliseconds: 100)); - verify(mockDiaryRepository.fillWakeup(diaryId: 1, time: '07:00')).called(1); + verify( + mockDiaryRepository.fillWakeup(diaryId: 1, time: '07:00'), + ).called(1); }); test('fillRetire - заполняет время отхода ко сну', () async { @@ -820,9 +1029,18 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.fillRetire(diaryId: anyNamed('diaryId'), time: anyNamed('time'))).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.fillRetire( + diaryId: anyNamed('diaryId'), + time: anyNamed('time'), + ), + ).thenAnswer((_) async => Future.value()); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -837,7 +1055,9 @@ void main() { await Future.delayed(const Duration(milliseconds: 100)); await diaryCubit!.fillRetire(diaryId: 1, time: '23:00'); await Future.delayed(const Duration(milliseconds: 100)); - verify(mockDiaryRepository.fillRetire(diaryId: 1, time: '23:00')).called(1); + verify( + mockDiaryRepository.fillRetire(diaryId: 1, time: '23:00'), + ).called(1); }); test('getDiary - создает новый день дневника', () async { @@ -849,39 +1069,59 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenAnswer((_) async => Future.value()); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); final result = await diaryCubit!.getDiary(); expect(result, isNotNull); - verify(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).called(1); + verify( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).called(1); verify(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).called(1); }); - test('getDiary - обрабатывает ошибку 422 и получает существующий день', () async { - diaryCubit = DiaryCubit( - diaryRepository: mockDiaryRepository, - glossaryRepository: mockGlossaryRepository, - profileRepository: mockProfileRepository, - dietRepository: mockDietRepository, - chatRepository: mockChatRepository, - settingsRepository: mockSettingsRepository, - ); - when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenThrow( - DioException( - requestOptions: RequestOptions(path: ''), - response: Response(requestOptions: RequestOptions(path: ''), statusCode: 422), - ), - ); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); + test( + 'getDiary - обрабатывает ошибку 422 и получает существующий день', + () async { + diaryCubit = DiaryCubit( + diaryRepository: mockDiaryRepository, + glossaryRepository: mockGlossaryRepository, + profileRepository: mockProfileRepository, + dietRepository: mockDietRepository, + chatRepository: mockChatRepository, + settingsRepository: mockSettingsRepository, + ); + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenThrow( + DioException( + requestOptions: RequestOptions(path: ''), + response: Response( + requestOptions: RequestOptions(path: ''), + statusCode: 422, + ), + ), + ); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); - final result = await diaryCubit!.getDiary(); + final result = await diaryCubit!.getDiary(); - expect(result, isNotNull); - verify(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).called(1); - verify(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).called(1); - }); + expect(result, isNotNull); + verify( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).called(1); + verify( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).called(1); + }, + ); test('getDiary - возвращает null при другой ошибке', () async { diaryCubit = DiaryCubit( @@ -895,7 +1135,10 @@ void main() { when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenThrow( DioException( requestOptions: RequestOptions(path: ''), - response: Response(requestOptions: RequestOptions(path: ''), statusCode: 500), + response: Response( + requestOptions: RequestOptions(path: ''), + statusCode: 500, + ), ), ); @@ -920,7 +1163,10 @@ void main() { when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenThrow( DioException( requestOptions: RequestOptions(path: ''), - response: Response(requestOptions: RequestOptions(path: ''), statusCode: 500), + response: Response( + requestOptions: RequestOptions(path: ''), + statusCode: 500, + ), ), ); @@ -941,12 +1187,25 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - const photo = DiaryPhotoModel(id: 1, originalName: 'test.jpg', path: 'path/to/test.jpg', size: 100); + const photo = DiaryPhotoModel( + id: 1, + originalName: 'test.jpg', + path: 'path/to/test.jpg', + size: 100, + ); when( - mockDiaryRepository.deletePhoto(photo: anyNamed('photo'), diaryId: anyNamed('diaryId'), mealId: anyNamed('mealId')), + mockDiaryRepository.deletePhoto( + photo: anyNamed('photo'), + diaryId: anyNamed('diaryId'), + mealId: anyNamed('mealId'), + ), ).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => testDiaryDay); - when(mockDiaryRepository.getNutritionData(any)).thenAnswer((_) async => testNutrition); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); when(mockSettingsRepository.getProfileSettings()).thenAnswer( (_) async => const ProfileSettingsModel( isMoodFillable: true, @@ -963,10 +1222,273 @@ void main() { await diaryCubit!.deletePhoto(photo: photo, diaryId: 1); await Future.delayed(const Duration(milliseconds: 100)); - verify(mockDiaryRepository.deletePhoto(photo: photo, diaryId: 1, mealId: 1)).called(1); + verify( + mockDiaryRepository.deletePhoto(photo: photo, diaryId: 1, mealId: 1), + ).called(1); }); - test('setSelectedDay - возвращает true даже если getDiary возвращает null', () async { + test( + 'setSelectedDay - возвращает true даже если getDiary возвращает null', + () async { + diaryCubit = DiaryCubit( + diaryRepository: mockDiaryRepository, + glossaryRepository: mockGlossaryRepository, + profileRepository: mockProfileRepository, + dietRepository: mockDietRepository, + chatRepository: mockChatRepository, + settingsRepository: mockSettingsRepository, + ); + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenThrow( + DioException( + requestOptions: RequestOptions(path: ''), + response: Response( + requestOptions: RequestOptions(path: ''), + statusCode: 500, + ), + ), + ); + + final result = await diaryCubit!.setSelectedDay(DateTime(2024, 1, 20)); + + // fetchDiaryV2 возвращает true когда getDiary() == null, так как эмитит состояние ошибки + expect(result, true); + expect(diaryCubit!.state, isA()); + }, + ); + + test( + 'fetchDiaryV2 - обрабатывает случай когда diaryEntity == null и нет диеты', + () async { + diaryCubit = DiaryCubit( + diaryRepository: mockDiaryRepository, + glossaryRepository: mockGlossaryRepository, + profileRepository: mockProfileRepository, + dietRepository: mockDietRepository, + chatRepository: mockChatRepository, + settingsRepository: mockSettingsRepository, + ); + // toEntity() возвращает null когда id == null + const diaryDayWithoutEntity = DiaryDayModel( + id: null, + date: '2024-01-15', + closed: 0, + comment: '', + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: false, + hasChosenPlan: false, + diaryState: null, + ), + meals: [], + chosenPlanId: null, + dayOfChosenDiet: null, + diet: null, + ); + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenAnswer((_) async => Future.value()); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => diaryDayWithoutEntity); + + final result = await diaryCubit!.fetchDiaryV2(needLoading: false); + + // Если diaryEntity == null (id == null) и нет диеты, fetchDiaryV2 возвращает false + // и эмитит предыдущее состояние (loading) + expect(result, false); + expect(diaryCubit!.state, const DiaryState.loading()); + }, + ); + + test( + 'fetchDiaryV2 - обрабатывает случай когда diaryEntity == null но есть диета', + () async { + diaryCubit = DiaryCubit( + diaryRepository: mockDiaryRepository, + glossaryRepository: mockGlossaryRepository, + profileRepository: mockProfileRepository, + dietRepository: mockDietRepository, + chatRepository: mockChatRepository, + settingsRepository: mockSettingsRepository, + ); + // id должен быть null, чтобы toEntity() вернул null и код пошел по ветке setDiaryForDietOnly + const diaryDayWithDiet = DiaryDayModel( + id: null, + date: '2024-01-15', + closed: 0, + comment: '', + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: true, + hasChosenPlan: false, + diaryState: null, + ), + meals: [], + chosenPlanId: null, + dayOfChosenDiet: 1, + diet: DiaryDietModel(id: 1, duration: 7, name: 'Test Diet'), + ); + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenAnswer((_) async => Future.value()); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => diaryDayWithDiet); + when(mockDietRepository.getDiet(1)).thenAnswer( + (_) async => const Diet( + id: 1, + slug: 'test-diet', + name: 'Test Diet', + image: '', + duration: 7, + state: DietState.active, + type: DietType(), + details: '', + dailySchedule: { + 1: { + 1: { + 1: DailySchedule( + name: 'Яблоко', + portion: Portion.grams, + quantity: 1, + ), + }, + }, + }, + author: Author( + authorSlug: 'test', + authorName: 'Test', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + wasLikedByMe: false, + isFavorite: false, + dailyNutrition: [], + ), + ); + + final result = await diaryCubit!.fetchDiaryV2(needLoading: false); + + expect(result, true); + expect(diaryCubit!.state, isA()); + }, + ); + + test( + 'fetchDiaryV2 - открывает будущий день диеты, когда API отдаёт last_state init', + () async { + diaryCubit = DiaryCubit( + diaryRepository: mockDiaryRepository, + glossaryRepository: mockGlossaryRepository, + profileRepository: mockProfileRepository, + dietRepository: mockDietRepository, + chatRepository: mockChatRepository, + settingsRepository: mockSettingsRepository, + ); + const diaryDayWithDiet = DiaryDayModel( + id: null, + date: '2024-01-16', + closed: 0, + comment: '', + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: true, + hasChosenPlan: false, + diaryState: DiaryStateEnum.init, + ), + meals: [], + chosenPlanId: null, + dayOfChosenDiet: 2, + diet: DiaryDietModel(id: 1, duration: 7, name: 'Test Diet'), + ); + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenAnswer((_) async => Future.value()); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => diaryDayWithDiet); + when(mockDietRepository.getDiet(1)).thenAnswer( + (_) async => const Diet( + id: 1, + slug: 'test-diet', + name: 'Test Diet', + image: '', + duration: 7, + state: DietState.active, + type: DietType(), + details: '', + dailySchedule: { + 2: { + 1: { + 1: DailySchedule( + name: 'Овсянка', + portion: Portion.grams, + quantity: 150, + productNutritionalValueId: 42, + dailyNutrition: DailyNutrition( + energy: 195, + proteins: 7, + fats: 4, + carbohydrates: 32, + ), + ), + }, + 2: { + 1: DailySchedule( + name: 'Гречка', + portion: Portion.pcs, + quantity: 2, + productNutritionalValueId: 7, + dailyNutrition: DailyNutrition( + energy: 220, + proteins: 8, + fats: 3, + carbohydrates: 40, + ), + ), + }, + }, + }, + author: Author( + authorSlug: 'test', + authorName: 'Test', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + wasLikedByMe: false, + isFavorite: false, + dailyNutrition: [], + ), + ); + + final result = await diaryCubit!.fetchDiaryV2(needLoading: false); + + expect(result, true); + expect(diaryCubit!.state, isA()); + final loaded = diaryCubit!.state as DiaryStateLoadedTomorrowWithDiet; + expect(loaded.diary.meals, hasLength(5)); + final oatmeal = loaded.diary.meals[0]; + expect(oatmeal.typeNumber, 1); + expect(oatmeal.portions.single.productName, 'Овсянка'); + expect(oatmeal.portions.single.productNutritionalValueId, 42); + expect( + oatmeal.portions.single.productCaloriesInfo?.calories, + closeTo(195 * 100 / 150, 0.001), + ); + final buckwheat = loaded.diary.meals[1]; + expect(buckwheat.typeNumber, 2); + expect(buckwheat.portions.single.productName, 'Гречка'); + expect(buckwheat.portions.single.productNutritionalValueId, 7); + expect(buckwheat.portions.single.productCaloriesInfo?.energyOnPortion, 220); + }, + ); + + test('fetchDiaryV2 - пустая диета не оставляет экран в загрузке', () async { diaryCubit = DiaryCubit( diaryRepository: mockDiaryRepository, glossaryRepository: mockGlossaryRepository, @@ -975,53 +1497,55 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenThrow( - DioException( - requestOptions: RequestOptions(path: ''), - response: Response(requestOptions: RequestOptions(path: ''), statusCode: 500), + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenAnswer((_) async {}); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => testDiaryDay); + when( + mockDiaryRepository.getNutritionData(any), + ).thenAnswer((_) async => testNutrition); + when(mockSettingsRepository.getProfileSettings()).thenAnswer( + (_) async => const ProfileSettingsModel( + isMoodFillable: true, + isBedtimeFillable: true, + isPublicProfile: true, + newUpdatesNotifications: null, + diaryReminderNotifications: null, + ), + ); + + expect(await diaryCubit!.setSelectedDay(DateTime(2024, 1, 15)), true); + await Future.delayed(const Duration(milliseconds: 50)); + expect(diaryCubit!.state, isA()); + + when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer( + (_) async => const DiaryDayModel( + id: null, + date: '2024-01-20', + closed: 0, + comment: '', + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: true, + hasChosenPlan: false, + diaryState: null, + ), + meals: [], + chosenPlanId: null, + dayOfChosenDiet: null, + diet: null, ), ); final result = await diaryCubit!.setSelectedDay(DateTime(2024, 1, 20)); - // fetchDiaryV2 возвращает true когда getDiary() == null, так как эмитит состояние ошибки - expect(result, true); - expect(diaryCubit!.state, isA()); - }); - - test('fetchDiaryV2 - обрабатывает случай когда diaryEntity == null и нет диеты', () async { - diaryCubit = DiaryCubit( - diaryRepository: mockDiaryRepository, - glossaryRepository: mockGlossaryRepository, - profileRepository: mockProfileRepository, - dietRepository: mockDietRepository, - chatRepository: mockChatRepository, - settingsRepository: mockSettingsRepository, - ); - // toEntity() возвращает null когда id == null - const diaryDayWithoutEntity = DiaryDayModel( - id: null, - date: '2024-01-15', - closed: 0, - comment: '', - typeOfDiary: TypeOfDiaryModel(hasChosenDiet: false, hasChosenPlan: false, diaryState: null), - meals: [], - chosenPlanId: null, - dayOfChosenDiet: null, - diet: null, - ); - when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => diaryDayWithoutEntity); - - final result = await diaryCubit!.fetchDiaryV2(needLoading: false); - - // Если diaryEntity == null (id == null) и нет диеты, fetchDiaryV2 возвращает false - // и эмитит предыдущее состояние (loading) expect(result, false); - expect(diaryCubit!.state, const DiaryState.loading()); + expect(diaryCubit!.state, isA()); + expect(diaryCubit!.selectedDay, DateTime(2024, 1, 15)); }); - test('fetchDiaryV2 - обрабатывает случай когда diaryEntity == null но есть диета', () async { + test('setSelectedDay - ошибка диеты оставляет выбранный день для повтора', () async { diaryCubit = DiaryCubit( diaryRepository: mockDiaryRepository, glossaryRepository: mockGlossaryRepository, @@ -1030,20 +1554,36 @@ void main() { chatRepository: mockChatRepository, settingsRepository: mockSettingsRepository, ); - // id должен быть null, чтобы toEntity() вернул null и код пошел по ветке setDiaryForDietOnly - const diaryDayWithDiet = DiaryDayModel( + const preview = DiaryDayModel( id: null, - date: '2024-01-15', + date: '2024-01-20', closed: 0, comment: '', - typeOfDiary: TypeOfDiaryModel(hasChosenDiet: true, hasChosenPlan: false, diaryState: null), + typeOfDiary: TypeOfDiaryModel( + hasChosenDiet: true, + hasChosenPlan: false, + diaryState: DiaryStateEnum.init, + ), meals: [], chosenPlanId: null, - dayOfChosenDiet: 1, + dayOfChosenDiet: 2, diet: DiaryDietModel(id: 1, duration: 7, name: 'Test Diet'), ); - when(mockDiaryRepository.createDiaryDay(day: anyNamed('day'))).thenAnswer((_) async => Future.value()); - when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer((_) async => diaryDayWithDiet); + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenAnswer((_) async {}); + when( + mockDiaryRepository.getDiaryDayV2(day: anyNamed('day')), + ).thenAnswer((_) async => preview); + when(mockDietRepository.getDiet(1)).thenThrow(Exception('network')); + + final day = DateTime(2024, 1, 20); + final result = await diaryCubit!.setSelectedDay(day); + + expect(result, false); + expect(diaryCubit!.state, isA()); + expect(diaryCubit!.selectedDay, day); + when(mockDietRepository.getDiet(1)).thenAnswer( (_) async => const Diet( id: 1, @@ -1055,11 +1595,22 @@ void main() { type: DietType(), details: '', dailySchedule: { - 1: { - 1: {1: DailySchedule(name: 'Яблоко', portion: Portion.grams, quantity: 1)}, + 2: { + 1: { + 1: DailySchedule( + name: 'Овсянка', + portion: Portion.grams, + quantity: 100, + ), + }, }, }, - author: Author(authorSlug: 'test', authorName: 'Test', authorProfileIcon: '', authorIsMe: false), + author: Author( + authorSlug: 'test', + authorName: 'Test', + authorProfileIcon: '', + authorIsMe: false, + ), totalLikes: 0, totalViews: 0, totalComments: 0, @@ -1069,12 +1620,118 @@ void main() { ), ); - final result = await diaryCubit!.fetchDiaryV2(needLoading: false); - await Future.delayed(const Duration(milliseconds: 100)); + final retry = await diaryCubit!.fetchDiaryV2(needLoading: true); - expect(result, true); - // setDiaryForDietOnly сначала эмитит loading, затем loadedTomorrowWithDiet - expect(diaryCubit!.state, isA()); + expect(retry, true); + final loaded = diaryCubit!.state as DiaryStateLoadedTomorrowWithDiet; + expect(loaded.diary.meals.first.portions.single.productName, 'Овсянка'); + expect(diaryCubit!.selectedDay, day); + }); + + test('setSelectedDay - поздний ответ не затирает более новый день', () async { + diaryCubit = DiaryCubit( + diaryRepository: mockDiaryRepository, + glossaryRepository: mockGlossaryRepository, + profileRepository: mockProfileRepository, + dietRepository: mockDietRepository, + chatRepository: mockChatRepository, + settingsRepository: mockSettingsRepository, + ); + DiaryDayModel preview(String date, int dietId) { + return DiaryDayModel( + id: null, + date: date, + closed: 0, + comment: '', + typeOfDiary: const TypeOfDiaryModel( + hasChosenDiet: true, + hasChosenPlan: false, + diaryState: DiaryStateEnum.init, + ), + meals: [], + chosenPlanId: null, + dayOfChosenDiet: 1, + diet: DiaryDietModel(id: dietId, duration: 7, name: 'Diet $dietId'), + ); + } + + Diet diet(int id, String product) { + return Diet( + id: id, + slug: 'diet-$id', + name: 'Diet $id', + image: '', + duration: 7, + state: DietState.active, + type: const DietType(), + details: '', + dailySchedule: { + 1: { + 1: { + 1: DailySchedule( + name: product, + portion: Portion.grams, + quantity: 100, + ), + }, + }, + }, + author: const Author( + authorSlug: 'test', + authorName: 'Test', + authorProfileIcon: '', + authorIsMe: false, + ), + totalLikes: 0, + totalViews: 0, + totalComments: 0, + wasLikedByMe: false, + isFavorite: false, + dailyNutrition: [], + ); + } + + when( + mockDiaryRepository.createDiaryDay(day: anyNamed('day')), + ).thenAnswer((_) async {}); + when(mockDiaryRepository.getDiaryDayV2(day: anyNamed('day'))).thenAnswer(( + invocation, + ) async { + final day = invocation.namedArguments[const Symbol('day')] as String; + if (day.startsWith('2024-01-20')) { + return preview('2024-01-20', 1); + } + return preview('2024-01-21', 2); + }); + final firstDiet = Completer(); + final secondDiet = Completer(); + var dietCalls = 0; + when(mockDietRepository.getDiet(any)).thenAnswer((invocation) { + dietCalls++; + final id = invocation.positionalArguments.first as int; + return (id == 1 ? firstDiet : secondDiet).future; + }); + + Future waitForDietCalls(int count) async { + for (var i = 0; i < 50 && dietCalls < count; i++) { + await Future.delayed(Duration.zero); + } + expect(dietCalls, greaterThanOrEqualTo(count)); + } + + final firstSelection = diaryCubit!.setSelectedDay(DateTime(2024, 1, 20)); + await waitForDietCalls(1); + final secondSelection = diaryCubit!.setSelectedDay(DateTime(2024, 1, 21)); + await waitForDietCalls(2); + + secondDiet.complete(diet(2, 'Новый')); + await secondSelection; + firstDiet.complete(diet(1, 'Старый')); + await firstSelection; + + final loaded = diaryCubit!.state as DiaryStateLoadedTomorrowWithDiet; + expect(loaded.diary.meals.first.portions.single.productName, 'Новый'); + expect(diaryCubit!.selectedDay, DateTime(2024, 1, 21)); }); }); } diff --git a/test/features/payment/presentation/widgets/promo_code_modal_test.dart b/test/features/payment/presentation/widgets/promo_code_modal_test.dart index 38199b8b..98293381 100644 --- a/test/features/payment/presentation/widgets/promo_code_modal_test.dart +++ b/test/features/payment/presentation/widgets/promo_code_modal_test.dart @@ -34,6 +34,7 @@ void main() { testWidgets('показывает заголовок Есть промокод? и кнопки Применить/Пропустить', (tester) async { await tester.pumpWidget(createTestWidget()); + await tester.pump(); await tester.tap(find.text('Open')); await tester.pumpAndSettle(); @@ -44,6 +45,7 @@ void main() { testWidgets('Применить с пустым полем показывает ошибку и не закрывает', (tester) async { await tester.pumpWidget(createTestWidget()); + await tester.pump(); await tester.tap(find.text('Open')); await tester.pumpAndSettle(); @@ -64,6 +66,7 @@ void main() { }, ), ); + await tester.pump(); await tester.tap(find.text('Open')); await tester.pumpAndSettle(); @@ -78,6 +81,7 @@ void main() { testWidgets('Пропустить закрывает шторку', (tester) async { await tester.pumpWidget(createTestWidget()); + await tester.pump(); await tester.tap(find.text('Open')); await tester.pumpAndSettle(); @@ -101,6 +105,7 @@ void main() { onRemove: () async => true, ), ); + await tester.pump(); await tester.tap(find.text('Open')); await tester.pumpAndSettle(); @@ -128,6 +133,7 @@ void main() { }, ), ); + await tester.pump(); await tester.tap(find.text('Open')); await tester.pumpAndSettle(); @@ -156,6 +162,7 @@ void main() { }, ), ); + await tester.pump(); await tester.tap(find.text('Open')); await tester.pumpAndSettle(); diff --git a/test/features/payment/presentation/widgets/sbp_banks_bottom_sheet_test.dart b/test/features/payment/presentation/widgets/sbp_banks_bottom_sheet_test.dart index 627105ac..2cd80ddd 100644 --- a/test/features/payment/presentation/widgets/sbp_banks_bottom_sheet_test.dart +++ b/test/features/payment/presentation/widgets/sbp_banks_bottom_sheet_test.dart @@ -98,6 +98,7 @@ void main() { await tester.pumpWidget(createTestWidget(planId: planId)); await tester.pump(); + await tester.pump(); expect(find.byType(Loader), findsOneWidget); expect(find.text('Сбербанк'), findsNothing); diff --git a/test/features/payment/presentation/widgets/sbp_qr_bottom_sheet_test.dart b/test/features/payment/presentation/widgets/sbp_qr_bottom_sheet_test.dart index 1d09ec3f..84136f03 100644 --- a/test/features/payment/presentation/widgets/sbp_qr_bottom_sheet_test.dart +++ b/test/features/payment/presentation/widgets/sbp_qr_bottom_sheet_test.dart @@ -106,6 +106,7 @@ void main() { Future openSheet(WidgetTester tester, {double? amount}) async { await pumpApp(tester, amount: amount); + await tester.pump(); await tester.tap(find.text('open')); await tester.pump(); await tester.pump(); diff --git a/test/features/plans/enums/chosen_plan_state_enum_test.dart b/test/features/plans/enums/chosen_plan_state_enum_test.dart index a82ef455..9f769b49 100644 --- a/test/features/plans/enums/chosen_plan_state_enum_test.dart +++ b/test/features/plans/enums/chosen_plan_state_enum_test.dart @@ -5,22 +5,70 @@ void main() { group('ChosenPlanStateEnum', () { test('has all expected values', () { expect(ChosenPlanStateEnum.values.length, 16); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateInited)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateStartDateHasBeenSet)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateInCoordination)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateStarted)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateInProgress)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.statePendingPayment)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateConfirmedByConsultant)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.statePaid)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateCanceledByTheInitiator)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateLastDayStarted)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateLastDayFinished)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateComplained)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateDone)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.personalDietSet)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.stateChargeWasCollected)); - expect(ChosenPlanStateEnum.values, contains(ChosenPlanStateEnum.statePaymentFailed)); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateInited), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateStartDateHasBeenSet), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateInCoordination), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateStarted), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateInProgress), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.statePendingPayment), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateConfirmedByConsultant), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.statePaid), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateCanceledByTheInitiator), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateLastDayStarted), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateLastDayFinished), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateComplained), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateDone), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.personalDietSet), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.stateChargeWasCollected), + ); + expect( + ChosenPlanStateEnum.values, + contains(ChosenPlanStateEnum.statePaymentFailed), + ); }); test('getShowableChatBadgeStates returns correct states', () { @@ -40,32 +88,77 @@ void main() { }); test('isStateAfterPaidState returns false for states before paid', () { - expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.isStateAfterPaidState(), isFalse); + expect( + ChosenPlanStateEnum.stateCanceledByTheInitiator.isStateAfterPaidState(), + isFalse, + ); expect(ChosenPlanStateEnum.stateInited.isStateAfterPaidState(), isFalse); - expect(ChosenPlanStateEnum.stateInCoordination.isStateAfterPaidState(), isFalse); - expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.isStateAfterPaidState(), isFalse); - expect(ChosenPlanStateEnum.statePendingPayment.isStateAfterPaidState(), isFalse); - expect(ChosenPlanStateEnum.statePaymentFailed.isStateAfterPaidState(), isFalse); + expect( + ChosenPlanStateEnum.stateInCoordination.isStateAfterPaidState(), + isFalse, + ); + expect( + ChosenPlanStateEnum.stateStartDateHasBeenSet.isStateAfterPaidState(), + isFalse, + ); + expect( + ChosenPlanStateEnum.statePendingPayment.isStateAfterPaidState(), + isFalse, + ); + expect( + ChosenPlanStateEnum.statePaymentFailed.isStateAfterPaidState(), + isFalse, + ); }); test('isStateAfterPaidState returns true for states after paid', () { expect(ChosenPlanStateEnum.statePaid.isStateAfterPaidState(), isTrue); expect(ChosenPlanStateEnum.stateStarted.isStateAfterPaidState(), isTrue); - expect(ChosenPlanStateEnum.stateInProgress.isStateAfterPaidState(), isTrue); - expect(ChosenPlanStateEnum.stateLastDayStarted.isStateAfterPaidState(), isTrue); - expect(ChosenPlanStateEnum.stateLastDayFinished.isStateAfterPaidState(), isTrue); - expect(ChosenPlanStateEnum.stateComplained.isStateAfterPaidState(), isTrue); + expect( + ChosenPlanStateEnum.stateInProgress.isStateAfterPaidState(), + isTrue, + ); + expect( + ChosenPlanStateEnum.stateLastDayStarted.isStateAfterPaidState(), + isTrue, + ); + expect( + ChosenPlanStateEnum.stateLastDayFinished.isStateAfterPaidState(), + isTrue, + ); + expect( + ChosenPlanStateEnum.stateComplained.isStateAfterPaidState(), + isTrue, + ); expect(ChosenPlanStateEnum.stateDone.isStateAfterPaidState(), isTrue); - expect(ChosenPlanStateEnum.personalDietSet.isStateAfterPaidState(), isTrue); - expect(ChosenPlanStateEnum.stateChargeWasCollected.isStateAfterPaidState(), isTrue); - expect(ChosenPlanStateEnum.stateConfirmedByConsultant.isStateAfterPaidState(), isTrue); + expect( + ChosenPlanStateEnum.personalDietSet.isStateAfterPaidState(), + isTrue, + ); + expect( + ChosenPlanStateEnum.stateChargeWasCollected.isStateAfterPaidState(), + isTrue, + ); + expect( + ChosenPlanStateEnum.stateConfirmedByConsultant.isStateAfterPaidState(), + isTrue, + ); }); test('canShowCancelAction returns true for cancellable states', () { expect(ChosenPlanStateEnum.stateInited.canShowCancelAction, isTrue); - expect(ChosenPlanStateEnum.stateInCoordination.canShowCancelAction, isTrue); - expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.canShowCancelAction, isTrue); - expect(ChosenPlanStateEnum.statePendingPayment.canShowCancelAction, isTrue); + expect( + ChosenPlanStateEnum.stateInCoordination.canShowCancelAction, + isTrue, + ); + expect( + ChosenPlanStateEnum.stateStartDateHasBeenSet.canShowCancelAction, + isTrue, + ); + expect( + ChosenPlanStateEnum.statePendingPayment.canShowCancelAction, + isTrue, + ); expect(ChosenPlanStateEnum.statePaid.canShowCancelAction, isTrue); expect(ChosenPlanStateEnum.stateStarted.canShowCancelAction, isTrue); expect(ChosenPlanStateEnum.stateInProgress.canShowCancelAction, isTrue); @@ -73,33 +166,129 @@ void main() { test('canShowCancelAction returns false for non-cancellable states', () { expect(ChosenPlanStateEnum.personalDietSet.canShowCancelAction, isFalse); - expect(ChosenPlanStateEnum.stateLastDayStarted.canShowCancelAction, isFalse); - expect(ChosenPlanStateEnum.stateLastDayFinished.canShowCancelAction, isFalse); + expect( + ChosenPlanStateEnum.stateLastDayStarted.canShowCancelAction, + isFalse, + ); + expect( + ChosenPlanStateEnum.stateLastDayFinished.canShowCancelAction, + isFalse, + ); expect(ChosenPlanStateEnum.stateComplained.canShowCancelAction, isFalse); expect(ChosenPlanStateEnum.stateDone.canShowCancelAction, isFalse); - expect(ChosenPlanStateEnum.stateChargeWasCollected.canShowCancelAction, isFalse); - expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.canShowCancelAction, isFalse); - expect(ChosenPlanStateEnum.statePaymentFailed.canShowCancelAction, isFalse); - expect(ChosenPlanStateEnum.stateConfirmedByConsultant.canShowCancelAction, isFalse); + expect( + ChosenPlanStateEnum.stateChargeWasCollected.canShowCancelAction, + isFalse, + ); + expect( + ChosenPlanStateEnum.stateCanceledByTheInitiator.canShowCancelAction, + isFalse, + ); + expect( + ChosenPlanStateEnum.statePaymentFailed.canShowCancelAction, + isFalse, + ); + expect( + ChosenPlanStateEnum.stateConfirmedByConsultant.canShowCancelAction, + isFalse, + ); }); - test('isCancelAfterPaidState returns true only for post-paid cancellable states', () { - expect(ChosenPlanStateEnum.statePaid.isCancelAfterPaidState, isTrue); - expect(ChosenPlanStateEnum.stateStarted.isCancelAfterPaidState, isTrue); - expect(ChosenPlanStateEnum.stateInProgress.isCancelAfterPaidState, isTrue); - expect(ChosenPlanStateEnum.stateInited.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.stateInCoordination.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.statePendingPayment.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.statePaymentFailed.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.stateConfirmedByConsultant.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.personalDietSet.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.stateLastDayStarted.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.stateLastDayFinished.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.stateComplained.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.stateDone.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.stateChargeWasCollected.isCancelAfterPaidState, isFalse); - expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.isCancelAfterPaidState, isFalse); + test( + 'isCancelAfterPaidState returns true only for post-paid cancellable states', + () { + expect(ChosenPlanStateEnum.statePaid.isCancelAfterPaidState, isTrue); + expect(ChosenPlanStateEnum.stateStarted.isCancelAfterPaidState, isTrue); + expect( + ChosenPlanStateEnum.stateInProgress.isCancelAfterPaidState, + isTrue, + ); + expect(ChosenPlanStateEnum.stateInited.isCancelAfterPaidState, isFalse); + expect( + ChosenPlanStateEnum.stateInCoordination.isCancelAfterPaidState, + isFalse, + ); + expect( + ChosenPlanStateEnum.stateStartDateHasBeenSet.isCancelAfterPaidState, + isFalse, + ); + expect( + ChosenPlanStateEnum.statePendingPayment.isCancelAfterPaidState, + isFalse, + ); + expect( + ChosenPlanStateEnum.statePaymentFailed.isCancelAfterPaidState, + isFalse, + ); + expect( + ChosenPlanStateEnum.stateConfirmedByConsultant.isCancelAfterPaidState, + isFalse, + ); + expect( + ChosenPlanStateEnum.personalDietSet.isCancelAfterPaidState, + isFalse, + ); + expect( + ChosenPlanStateEnum.stateLastDayStarted.isCancelAfterPaidState, + isFalse, + ); + expect( + ChosenPlanStateEnum.stateLastDayFinished.isCancelAfterPaidState, + isFalse, + ); + expect( + ChosenPlanStateEnum.stateComplained.isCancelAfterPaidState, + isFalse, + ); + expect(ChosenPlanStateEnum.stateDone.isCancelAfterPaidState, isFalse); + expect( + ChosenPlanStateEnum.stateChargeWasCollected.isCancelAfterPaidState, + isFalse, + ); + expect( + ChosenPlanStateEnum + .stateCanceledByTheInitiator + .isCancelAfterPaidState, + isFalse, + ); + }, + ); + + test( + 'allowsVideoCall is false for finished and canceled consultations', + () { + expect( + ChosenPlanStateEnum.stateCanceledByTheInitiator.allowsVideoCall, + isFalse, + ); + expect(ChosenPlanStateEnum.statePaymentFailed.allowsVideoCall, isFalse); + expect(ChosenPlanStateEnum.stateDone.allowsVideoCall, isFalse); + expect( + ChosenPlanStateEnum.stateChargeWasCollected.allowsVideoCall, + isFalse, + ); + }, + ); + + test('allowsVideoCall is true while the consultation is not finished', () { + expect(ChosenPlanStateEnum.stateInited.allowsVideoCall, isTrue); + expect(ChosenPlanStateEnum.stateInCoordination.allowsVideoCall, isTrue); + expect( + ChosenPlanStateEnum.stateStartDateHasBeenSet.allowsVideoCall, + isTrue, + ); + expect(ChosenPlanStateEnum.statePendingPayment.allowsVideoCall, isTrue); + expect( + ChosenPlanStateEnum.stateConfirmedByConsultant.allowsVideoCall, + isTrue, + ); + expect(ChosenPlanStateEnum.statePaid.allowsVideoCall, isTrue); + expect(ChosenPlanStateEnum.personalDietSet.allowsVideoCall, isTrue); + expect(ChosenPlanStateEnum.stateStarted.allowsVideoCall, isTrue); + expect(ChosenPlanStateEnum.stateInProgress.allowsVideoCall, isTrue); + expect(ChosenPlanStateEnum.stateLastDayStarted.allowsVideoCall, isTrue); + expect(ChosenPlanStateEnum.stateLastDayFinished.allowsVideoCall, isTrue); + expect(ChosenPlanStateEnum.stateComplained.allowsVideoCall, isTrue); }); test('getActiveStates returns correct states', () { @@ -114,8 +303,10 @@ void main() { expect(activeStates, contains(ChosenPlanStateEnum.stateComplained)); expect(activeStates, contains(ChosenPlanStateEnum.stateDone)); expect(activeStates, contains(ChosenPlanStateEnum.personalDietSet)); - expect(activeStates, isNot(contains(ChosenPlanStateEnum.statePaymentFailed))); + expect( + activeStates, + isNot(contains(ChosenPlanStateEnum.statePaymentFailed)), + ); }); }); } - diff --git a/test/features/settings/presentation/bloc/settings_cubit_test.dart b/test/features/settings/presentation/bloc/settings_cubit_test.dart index 674492c4..9cc0ad17 100644 --- a/test/features/settings/presentation/bloc/settings_cubit_test.dart +++ b/test/features/settings/presentation/bloc/settings_cubit_test.dart @@ -141,12 +141,46 @@ void main() { await settingsCubit!.init(); await Future.delayed(const Duration(milliseconds: 100)); - await settingsCubit!.updateProfileDetails(profileDetailsModel: SettingsFixtures.profileDetailsModel()); + final result = await settingsCubit!.updateProfileDetails(profileDetailsModel: SettingsFixtures.profileDetailsModel()); await Future.delayed(const Duration(milliseconds: 100)); + expect(result, true); verify(mockSettingsRepository.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).called(1); }); + test('updateProfileDetails - возвращает false при ошибке и перезагружает состояние', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, + ); + + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + when(mockProfileRepository.getMyProfileDetails()) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + when(mockSettingsRepository.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))) + .thenThrow(Exception('Ошибка сохранения')); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 100)); + final result = await settingsCubit!.updateProfileDetails(profileDetailsModel: SettingsFixtures.profileDetailsModel()); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(result, false); + expect(settingsCubit!.state, isA()); + }); + test('updateProfileSettings - обновляет настройки профиля', () async { settingsCubit = SettingsCubit( profileRepository: mockProfileRepository, @@ -173,12 +207,46 @@ void main() { await settingsCubit!.init(); await Future.delayed(const Duration(milliseconds: 100)); - await settingsCubit!.updateProfileSettings(profileSettingsModel: SettingsFixtures.profileSettingsModel()); + final result = await settingsCubit!.updateProfileSettings(profileSettingsModel: SettingsFixtures.profileSettingsModel()); await Future.delayed(const Duration(milliseconds: 100)); + expect(result, true); verify(mockSettingsRepository.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).called(1); }); + test('updateProfileSettings - возвращает false при ошибке и перезагружает состояние', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, + ); + + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + when(mockProfileRepository.getMyProfileDetails()) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + when(mockSettingsRepository.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))) + .thenThrow(Exception('Ошибка сохранения')); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 100)); + final result = await settingsCubit!.updateProfileSettings(profileSettingsModel: SettingsFixtures.profileSettingsModel()); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(result, false); + expect(settingsCubit!.state, isA()); + }); + test('deleteAccount - удаляет аккаунт', () async { settingsCubit = SettingsCubit( profileRepository: mockProfileRepository, diff --git a/test/features/settings/presentation/pages/general_info_screen_test.dart b/test/features/settings/presentation/pages/general_info_screen_test.dart index 1d302215..5299b133 100644 --- a/test/features/settings/presentation/pages/general_info_screen_test.dart +++ b/test/features/settings/presentation/pages/general_info_screen_test.dart @@ -13,6 +13,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/pages/general_info_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -25,6 +26,8 @@ import 'general_info_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('GeneralInfoScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -32,6 +35,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -95,7 +113,20 @@ void main() { supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -112,7 +143,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); @@ -122,8 +153,8 @@ void main() { child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(GeneralInfoScreen), findsOneWidget); }); @@ -136,13 +167,13 @@ void main() { profile: mockProfile, hasActiveConsultation: false, ); - final saveCompleter = Completer(); + final saveCompleter = Completer(); when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) => saveCompleter.future); - when(cubit.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).thenAnswer((_) async {}); + when(cubit.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); @@ -152,7 +183,8 @@ void main() { child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.text('Сохранить'), findsOneWidget); expect(find.byType(Loader), findsNothing); @@ -167,12 +199,88 @@ void main() { final loaderSize = tester.getSize(find.byType(Loader)); expect(loaderSize.height, lessThan(60)); - saveCompleter.complete(); + saveCompleter.complete(true); + await tester.pump(); + await tester.pumpAndSettle(); + + expect(find.byType(GeneralInfoScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('показывает уведомление после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + when(cubit.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); - expect(find.text('Сохранить'), findsOneWidget); - expect(find.byType(Loader), findsNothing); + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pumpAndSettle(); + expect(find.byType(GeneralInfoScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление, если сохранение не удалось', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + when(cubit.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(GeneralInfoScreen), findsOneWidget); }); }); } diff --git a/test/features/settings/presentation/pages/other_info_screen_test.dart b/test/features/settings/presentation/pages/other_info_screen_test.dart index ee437678..71767cf2 100644 --- a/test/features/settings/presentation/pages/other_info_screen_test.dart +++ b/test/features/settings/presentation/pages/other_info_screen_test.dart @@ -10,6 +10,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/pages/other_info_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -22,6 +23,8 @@ import 'other_info_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('OtherInfoScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -29,6 +32,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -92,7 +110,20 @@ void main() { supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -109,9 +140,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async { - return Future.value(); - }); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); @@ -121,10 +150,82 @@ void main() { child: wrap(OtherInfoScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(OtherInfoScreen), findsOneWidget); }); + + testWidgets('показывает уведомление и возвращается к настройкам после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(OtherInfoScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pumpAndSettle(); + expect(find.byType(OtherInfoScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление и остаётся на экране при ошибке сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(OtherInfoScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(OtherInfoScreen), findsOneWidget); + }); }); } diff --git a/test/features/settings/presentation/pages/physical_activity_screen_test.dart b/test/features/settings/presentation/pages/physical_activity_screen_test.dart index 10d4a46b..2b849d89 100644 --- a/test/features/settings/presentation/pages/physical_activity_screen_test.dart +++ b/test/features/settings/presentation/pages/physical_activity_screen_test.dart @@ -8,7 +8,9 @@ import 'package:eatvio_app/features/settings/models/profile_settings_model.dart' import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/features/settings/presentation/pages/physical_activity_screen.dart'; +import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -21,6 +23,8 @@ import 'physical_activity_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('PhysicalActivityScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -28,6 +32,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -87,9 +106,24 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -106,7 +140,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); @@ -116,10 +150,82 @@ void main() { child: wrap(PhysicalActivityScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(PhysicalActivityScreen), findsOneWidget); }); + + testWidgets('показывает уведомление и возвращается к настройкам после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PhysicalActivityScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pumpAndSettle(); + expect(find.byType(PhysicalActivityScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление и остаётся на экране при ошибке сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PhysicalActivityScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(PhysicalActivityScreen), findsOneWidget); + }); }); } diff --git a/test/features/settings/presentation/pages/physical_form_screen_test.dart b/test/features/settings/presentation/pages/physical_form_screen_test.dart index bc86fdda..43fb07b8 100644 --- a/test/features/settings/presentation/pages/physical_form_screen_test.dart +++ b/test/features/settings/presentation/pages/physical_form_screen_test.dart @@ -10,6 +10,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/pages/physical_form_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -22,6 +23,8 @@ import 'physical_form_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('PhysicalFormScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -29,6 +32,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -92,7 +110,20 @@ void main() { supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -109,7 +140,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); @@ -119,10 +150,82 @@ void main() { child: wrap(PhysicalFormScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(PhysicalFormScreen), findsOneWidget); }); + + testWidgets('показывает уведомление и возвращается к настройкам после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PhysicalFormScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pumpAndSettle(); + expect(find.byType(PhysicalFormScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление и остаётся на экране при ошибке сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PhysicalFormScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(PhysicalFormScreen), findsOneWidget); + }); }); } diff --git a/test/features/settings/presentation/pages/pressure_screen_test.dart b/test/features/settings/presentation/pages/pressure_screen_test.dart index 309597f9..1f3a1306 100644 --- a/test/features/settings/presentation/pages/pressure_screen_test.dart +++ b/test/features/settings/presentation/pages/pressure_screen_test.dart @@ -10,6 +10,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/pages/pressure_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -22,6 +23,8 @@ import 'pressure_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('PressureScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -29,6 +32,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -92,7 +110,20 @@ void main() { supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -109,7 +140,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); @@ -119,10 +150,82 @@ void main() { child: wrap(PressureScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(PressureScreen), findsOneWidget); }); + + testWidgets('показывает уведомление и возвращается к настройкам после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PressureScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pumpAndSettle(); + expect(find.byType(PressureScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление и остаётся на экране при ошибке сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PressureScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(PressureScreen), findsOneWidget); + }); }); } diff --git a/test/features/video_calls/recordings/presentation/pages/video_call_recordings_screen_test.dart b/test/features/video_calls/recordings/presentation/pages/video_call_recordings_screen_test.dart new file mode 100644 index 00000000..fd92c720 --- /dev/null +++ b/test/features/video_calls/recordings/presentation/pages/video_call_recordings_screen_test.dart @@ -0,0 +1,162 @@ +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/models/pagination_model.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_status.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart'; +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:network_image_mock/network_image_mock.dart'; + +class _MockRecordingsRepository extends Mock implements VideoCallRecordingsRepository {} + +void main() { + late _MockRecordingsRepository repository; + + VideoCallRecordingsPagination page( + List data, { + int lastPage = 1, + }) { + return VideoCallRecordingsPagination( + data: data, + links: const Links( + first: 'https://example.com?page=1', + last: 'https://example.com?page=1', + prev: null, + next: null, + ), + meta: Meta( + currentPage: 1, + from: data.isEmpty ? null : 1, + lastPage: lastPage, + links: const [], + perPage: 20, + to: data.isEmpty ? null : data.length, + total: data.length, + ), + ); + } + + VideoCallRecordingModel recording(int id) { + return VideoCallRecordingModel( + id: id, + status: RecordingStatus.ready, + durationSeconds: 60, + createdAt: DateTime.utc(2026, 9, 21, 10), + previewUrl: 'https://example.com/preview.jpg', + fileUrl: 'https://example.com/file.mp4', + counterpart: const VideoCallRecordingCounterpartModel(name: 'Сидни', slug: 'sydney'), + ); + } + + setUp(() async { + await sl.reset(); + repository = _MockRecordingsRepository(); + sl.registerFactory( + () => VideoCallRecordingsCubit(repository: repository), + ); + }); + + tearDown(() async { + await sl.reset(); + }); + + Widget wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], + supportedLocales: const [Locale('ru')], + home: child, + ); + } + + testWidgets('short list can be pulled to refresh', (tester) async { + await mockNetworkImagesFor(() async { + when(() => repository.getRecordings(page: 1, period: null)).thenAnswer( + (_) async => page([recording(1)]), + ); + + await tester.pumpWidget(wrap(const VideoCallRecordingsScreen())); + await tester.pumpAndSettle(); + + final list = tester.widget(find.byType(ListView)); + expect(list.physics, isA()); + + await tester.fling(find.byType(ListView), const Offset(0, 400), 1200); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + + verify(() => repository.getRecordings(page: 1, period: null)).called(2); + }); + }); + + testWidgets('pull on a short list does not request the next page', (tester) async { + await mockNetworkImagesFor(() async { + when(() => repository.getRecordings(page: 1, period: null)).thenAnswer( + (_) async => page([recording(1)], lastPage: 2), + ); + when(() => repository.getRecordings(page: 2, period: null)).thenAnswer( + (_) async => page([recording(2)], lastPage: 2), + ); + + await tester.pumpWidget(wrap(const VideoCallRecordingsScreen())); + await tester.pumpAndSettle(); + + await tester.fling(find.byType(ListView), const Offset(0, 400), 1200); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + + verifyNever(() => repository.getRecordings(page: 2, period: null)); + }); + }); + + testWidgets('empty state text stays visible at a large text scale', (tester) async { + tester.view.physicalSize = const Size(320, 240); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + when(() => repository.getRecordings(page: 1, period: null)).thenAnswer( + (_) async => page(const []), + ); + + await tester.pumpWidget( + wrap( + const MediaQuery( + data: MediaQueryData(textScaler: TextScaler.linear(3)), + child: VideoCallRecordingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Пока нет видеоконсультаций'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('empty list can be pulled to refresh', (tester) async { + when(() => repository.getRecordings(page: 1, period: null)).thenAnswer( + (_) async => page(const []), + ); + + await tester.pumpWidget(wrap(const VideoCallRecordingsScreen())); + await tester.pumpAndSettle(); + + expect(find.text('Пока нет видеоконсультаций'), findsOneWidget); + final list = tester.widget(find.byType(ListView)); + expect(list.physics, isA()); + + await tester.fling(find.text('Пока нет видеоконсультаций'), const Offset(0, 400), 1200); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + + verify(() => repository.getRecordings(page: 1, period: null)).called(2); + }); +} diff --git a/test/features/video_calls/recordings/services/video_call_recording_file_service_test.dart b/test/features/video_calls/recordings/services/video_call_recording_file_service_test.dart index 760f1cee..aef2bba7 100644 --- a/test/features/video_calls/recordings/services/video_call_recording_file_service_test.dart +++ b/test/features/video_calls/recordings/services/video_call_recording_file_service_test.dart @@ -14,6 +14,7 @@ class _MockDio extends Mock implements Dio {} class _FakeDownloadsSaver extends Fake implements PublicDownloadsSaver { String? lastSourcePath; String? lastFileName; + String? lastSubfolder; @override Future saveToDownloads({ @@ -24,7 +25,8 @@ class _FakeDownloadsSaver extends Fake implements PublicDownloadsSaver { }) async { lastSourcePath = sourcePath; lastFileName = fileName; - return 'content://downloads/Itvio/$fileName'; + lastSubfolder = subfolder; + return 'content://downloads/$subfolder/$fileName'; } } @@ -157,7 +159,8 @@ void main() { ); expect(downloadsSaver.lastFileName, 'recording_1.mp4'); - expect(saved, contains('Itvio')); + expect(downloadsSaver.lastSubfolder, 'Eatvio'); + expect(saved, contains('Eatvio')); expect(File(downloadsSaver.lastSourcePath!).existsSync(), isFalse); }); } diff --git a/test/features/video_calls/widgets/video_call_name_label_test.dart b/test/features/video_calls/widgets/video_call_name_label_test.dart index 8562ea52..ede13cc1 100644 --- a/test/features/video_calls/widgets/video_call_name_label_test.dart +++ b/test/features/video_calls/widgets/video_call_name_label_test.dart @@ -19,6 +19,7 @@ void main() { testWidgets('VideoCallParticipantNameLabel renders consultant role above name', (tester) async { await tester.pumpWidget( MaterialApp( + locale: const Locale('en'), localizationsDelegates: const [S.delegate, ...GlobalMaterialLocalizations.delegates], supportedLocales: S.delegate.supportedLocales, home: const Scaffold( @@ -26,6 +27,7 @@ void main() { ), ), ); + await tester.pump(); expect(find.text('Alex'), findsOneWidget); expect(find.text('Eatvio consultant'), findsOneWidget);