Compare commits

...

10 Commits

17 changed files with 15659 additions and 11772 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -388,7 +388,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Distribution: ITVIO, OOO (VL68C36HYS)";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 81;
CURRENT_PROJECT_VERSION = 83;
DEVELOPMENT_TEAM = VL68C36HYS;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
@@ -406,7 +406,7 @@
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
MARKETING_VERSION = 1.3.4;
MARKETING_VERSION = 1.3.3;
PRODUCT_BUNDLE_IDENTIFIER = com.eatvioapp.app;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "match AppStore com.eatvioapp.app 1747050044";
@@ -539,7 +539,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Distribution: ITVIO, OOO (VL68C36HYS)";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 81;
CURRENT_PROJECT_VERSION = 83;
DEVELOPMENT_TEAM = VL68C36HYS;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
@@ -557,7 +557,7 @@
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
MARKETING_VERSION = 1.3.4;
MARKETING_VERSION = 1.3.3;
PRODUCT_BUNDLE_IDENTIFIER = com.eatvioapp.app;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "match AppStore com.eatvioapp.app 1747050044";
@@ -578,7 +578,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Distribution: ITVIO, OOO (VL68C36HYS)";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 81;
CURRENT_PROJECT_VERSION = 83;
DEVELOPMENT_TEAM = VL68C36HYS;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
@@ -596,7 +596,7 @@
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
MARKETING_VERSION = 1.3.4;
MARKETING_VERSION = 1.3.3;
PRODUCT_BUNDLE_IDENTIFIER = com.eatvioapp.app;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "match AppStore com.eatvioapp.app 1747050044";

View File

@@ -135,12 +135,12 @@ class _ChatScreenState extends State<ChatScreen> {
} else if (!amIConsultant &&
(chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateStartDateHasBeenSet || chosenPlan.chosenPlanState == ChosenPlanStateEnum.statePendingPayment)) {
bannerType = BannerType.payment;
} else if (chosenOption?.hasPersonalDiet == true && amIConsultant) {
bannerType = BannerType.setPersonalDiet;
} else if (chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateDone && amIConsultant) {
bannerType = BannerType.collectCharge;
} else if (chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateLastDayFinished && !amIConsultant) {
bannerType = BannerType.finishPlan;
} else if (chosenOption?.hasPersonalDiet == true && amIConsultant && chosenPlan.chosenPlanState != ChosenPlanStateEnum.stateDone) {
bannerType = BannerType.setPersonalDiet;
}
return Scaffold(

View File

@@ -29,7 +29,7 @@ class AuthorCard extends StatelessWidget {
child: Stack(
children: [
Padding(
padding: const EdgeInsets.only(left: 16, top: 16, bottom: 24),
padding: const EdgeInsets.only(left: 16, top: 16, bottom: 24, right: 16),
child: Column(
children: [
ListTile(
@@ -68,20 +68,23 @@ class AuthorCard extends StatelessWidget {
if (author.authorPlaceInRating != null)
InfoBouble(
radius: 12,
backgroundColor: appTheme.whiteA700,
backgroundColor: appTheme.cardBackground,
children: [
Text('${author.authorPlaceInRating}-й в рейтинге', style: TextStyles.textMMediumAuto.copyWith(color: appTheme.blueA400)),
],
),
] else
GestureDetector(
onTap: () {
GoRouter.of(context).pushNamed(UserDetailsScreen.name, extra: customerProfile!.slug);
},
child: InfoBouble(
radius: 12,
backgroundColor: appTheme.whiteA700,
children: [Text('Анкета пользователя', style: TextStyles.textMMediumAuto.copyWith(color: appTheme.blueA400))],
Expanded(
child: GestureDetector(
onTap: () {
GoRouter.of(context).pushNamed(UserDetailsScreen.name, extra: customerProfile!.slug);
},
child: InfoBouble(
radius: 12,
backgroundColor: appTheme.cardBackground,
mainAxisAlignment: MainAxisAlignment.center,
children: [Text('Анкета пользователя', style: TextStyles.textMMediumAuto.copyWith(color: appTheme.blueA400))],
),
),
),
],

View File

@@ -2,20 +2,25 @@ import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:flutter/material.dart';
class InfoBouble extends StatelessWidget {
const InfoBouble({super.key, required this.children, this.backgroundColor, this.radius = 100, this.padding});
const InfoBouble({
super.key,
required this.children,
this.backgroundColor,
this.radius = 100,
this.padding,
this.mainAxisAlignment = MainAxisAlignment.start,
});
final List<Widget> children;
final Color? backgroundColor;
final double radius;
final EdgeInsetsGeometry? padding;
final MainAxisAlignment mainAxisAlignment;
@override
Widget build(BuildContext context) {
return Container(
padding: padding ?? const EdgeInsets.symmetric(horizontal: 12, vertical: 8.5),
decoration: BoxDecoration(
color: backgroundColor ?? appTheme.gray50,
borderRadius: BorderRadius.circular(radius),
),
child: Row(mainAxisSize: MainAxisSize.min, children: children),
decoration: BoxDecoration(color: backgroundColor ?? appTheme.gray50, borderRadius: BorderRadius.circular(radius)),
child: Row(mainAxisSize: MainAxisSize.min, mainAxisAlignment: mainAxisAlignment, children: children),
);
}
}

View File

@@ -316,7 +316,7 @@ class ChosenPlanFinishedToConsultantNotification implements BaseNotificationMode
type: type,
planName: json['plan_name'],
customerName: json['client_name'],
planId: json['plan_id'],
planId: json['chosen_plan_id'],
isRead: isRead ?? false,
createdAt: parseDate(createdAt ?? json['created_at'] ?? DateTime.now().toIso8601String()),
);
@@ -1695,6 +1695,35 @@ class DiaryReminderForUsersNotification implements BaseNotificationModel {
}
}
class PersonalDietIsDefinedToCustomerNotification implements BaseNotificationModel {
@override
final NotificationType type;
@override
final bool isRead;
@override
final DateTime createdAt;
final String dietName;
final int dietId;
PersonalDietIsDefinedToCustomerNotification({
required this.type,
required this.isRead,
required this.createdAt,
required this.dietName,
required this.dietId,
});
factory PersonalDietIsDefinedToCustomerNotification.fromJson(Map<String, dynamic> json, NotificationType type, {bool? isRead, String? createdAt}) {
return PersonalDietIsDefinedToCustomerNotification(
type: type,
isRead: isRead ?? false,
createdAt: parseDate(createdAt ?? json['created_at'] ?? DateTime.now().toIso8601String()),
dietName: json['diet_name'] ?? '',
dietId: json['diet_id'],
);
}
}
enum NotificationType {
// Diet related
dietCancelled,
@@ -1726,6 +1755,7 @@ enum NotificationType {
userDailyReportCompleted,
chosenPlanFinishedToConsultant,
stayOnTrackToCustomer,
personalDietIsDefinedToCustomer,
// Comments
entityCommented,
@@ -1834,6 +1864,7 @@ enum NotificationType {
'chosen-plan-finished-to-consultant' => NotificationType.chosenPlanFinishedToConsultant,
'stay-on-track-to-customer' => NotificationType.stayOnTrackToCustomer,
'diary-reminder-for-users' => NotificationType.diaryReminderForUsers,
'personal-diet-is-defined-to-customer' => NotificationType.personalDietIsDefinedToCustomer,
// Legacy mapping
'App\\Notifications\\Plan\\PlanSubscriptionStartedToAuthor' => NotificationType.planSubscriptionStartedToAuthor,

View File

@@ -261,6 +261,12 @@ class NotificationsCubit extends Cubit<NotificationsState> {
createdAt: createdAt,
),
NotificationType.diaryReminderForUsers => DiaryReminderForUsersNotification.fromJson(notificationJson, type, isRead: isRead, createdAt: createdAt),
NotificationType.personalDietIsDefinedToCustomer => PersonalDietIsDefinedToCustomerNotification.fromJson(
notificationJson,
type,
isRead: isRead,
createdAt: createdAt,
),
NotificationType.unknown => UnknownNotification(type: type),
};
} catch (e) {

View File

@@ -1,3 +1,4 @@
import 'package:eatvio_app/core/routing/route_constants.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/utils/date_time_utils.dart';
@@ -113,7 +114,11 @@ class NotificationWidget extends StatelessWidget {
notification: notification as ProductStatusUpdatedForAuthorNotification,
),
DiaryReminderForUsersNotification() => _DiaryReminderForUsersWidget(notification: notification as DiaryReminderForUsersNotification),
PersonalDietIsDefinedToCustomerNotification() => _PersonalDietIsDefinedToCustomerWidget(
notification: notification as PersonalDietIsDefinedToCustomerNotification,
),
UnknownNotification() => _UnknownNotificationWidget(notification: notification as UnknownNotification),
// TODO: Handle this case.
};
}
}
@@ -364,34 +369,38 @@ class _ChosenPlanFinishedToConsultantWidget extends StatelessWidget {
// CardSettingsScreen
class _BaseNotificationWidget extends StatelessWidget {
const _BaseNotificationWidget({required this.notificationsText, required this.isRead, required this.createdAt});
const _BaseNotificationWidget({required this.notificationsText, required this.isRead, required this.createdAt, this.onTap});
final String notificationsText;
final bool isRead;
final DateTime createdAt;
final void Function()? onTap;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(notificationsText, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
),
if (!isRead)
Container(
decoration: BoxDecoration(color: appTheme.blueA400, shape: BoxShape.circle),
width: 8,
height: 8,
return GestureDetector(
onTap: onTap,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(notificationsText, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
),
],
),
const SizedBox(height: 4),
Text(
'${createdAt.day} ${_getMonthName(createdAt.month)} ${createdAt.hour.toString().padLeft(2, '0')}:${createdAt.minute.toString().padLeft(2, '0')}',
style: TextStyles.textSMedium.copyWith(color: appTheme.gray600),
),
],
if (!isRead)
Container(
decoration: BoxDecoration(color: appTheme.blueA400, shape: BoxShape.circle),
width: 8,
height: 8,
),
],
),
const SizedBox(height: 4),
Text(
'${createdAt.day} ${_getMonthName(createdAt.month)} ${createdAt.hour.toString().padLeft(2, '0')}:${createdAt.minute.toString().padLeft(2, '0')}',
style: TextStyles.textSMedium.copyWith(color: appTheme.gray600),
),
],
),
);
}
@@ -1053,3 +1062,17 @@ class _DiaryReminderForUsersWidget extends StatelessWidget {
return _BaseNotificationWidget(isRead: notification.isRead, notificationsText: 'Напоминание о заполнении дневника', createdAt: notification.createdAt);
}
}
class _PersonalDietIsDefinedToCustomerWidget extends StatelessWidget {
const _PersonalDietIsDefinedToCustomerWidget({required this.notification});
final PersonalDietIsDefinedToCustomerNotification notification;
@override
Widget build(BuildContext context) {
return _BaseNotificationWidget(
isRead: notification.isRead,
onTap: () => GoRouter.of(context).push(RouteConstants.aboutDietScreen, extra: {'id': notification.dietId, 'navigateToComments': false}),
notificationsText: 'Персональная диета "${notification.dietName}" установлена',
createdAt: notification.createdAt,
);
}
}

View File

@@ -407,6 +407,12 @@ class NotificationsService {
isRead: readDate != null,
createdAt: createdAt,
),
NotificationType.personalDietIsDefinedToCustomer => PersonalDietIsDefinedToCustomerNotification.fromJson(
notificationJson['data'],
type,
isRead: readDate != null,
createdAt: createdAt,
),
NotificationType.unknown => UnknownNotification(type: type, createdAt: parseDate(createdAt)),
};
} catch (e) {

View File

@@ -11,11 +11,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
class PaymentBanner extends StatefulWidget {
const PaymentBanner({
super.key,
required this.successfulPayment,
});
const PaymentBanner({super.key, required this.successfulPayment});
final bool successfulPayment;
@override
@@ -29,8 +25,9 @@ class _PaymentBannerState extends State<PaymentBanner> {
final s = S.of(context);
final size = MediaQuery.sizeOf(context);
return MainBackgroundBouble(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Stack(children: [
padding: const EdgeInsets.symmetric(vertical: 16),
child: Stack(
children: [
Positioned(
left: 0,
top: 0,
@@ -38,8 +35,9 @@ class _PaymentBannerState extends State<PaymentBanner> {
child: Container(
width: 4,
decoration: BoxDecoration(
color: widget.successfulPayment ? appTheme.blueA400 : appTheme.strongRed,
borderRadius: const BorderRadius.only(topRight: Radius.circular(20), bottomRight: Radius.circular(20))),
color: widget.successfulPayment ? appTheme.blueA400 : appTheme.strongRed,
borderRadius: const BorderRadius.only(topRight: Radius.circular(20), bottomRight: Radius.circular(20)),
),
),
),
Padding(
@@ -50,78 +48,65 @@ class _PaymentBannerState extends State<PaymentBanner> {
? [
SizedBox(
width: size.width * 0.6,
child: Text(
s.cunsutation_was_paid_successfully,
style: TextStyles.textLSemibold.copyWith(color: appTheme.black),
),
),
const SizedBox(
height: 8,
child: Text(s.cunsutation_was_paid_successfully, style: TextStyles.textLSemibold.copyWith(color: appTheme.black)),
),
const SizedBox(height: 8),
SizedBox(
width: size.width * 0.6,
child: Text(
s.wait_for_start_day,
style: TextStyles.textMMediumAuto.copyWith(color: appTheme.black),
),
),
const SizedBox(
height: 16,
child: Text(s.wait_for_start_day, style: TextStyles.textMMediumAuto.copyWith(color: appTheme.black)),
),
const SizedBox(height: 16),
isLoading
? const Center(child: Loader())
: CustomOutlinedButton(
text: s.go_to_diary,
height: 52,
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700),
buttonStyle:
ButtonStyle(side: const WidgetStatePropertyAll(BorderSide.none), backgroundColor: WidgetStatePropertyAll(appTheme.blueA400)),
buttonStyle: ButtonStyle(
side: const WidgetStatePropertyAll(BorderSide.none),
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
),
onPressed: () async {
GoRouter.of(context).pushReplacement('/diary-screen');
},
),
const SizedBox(height: 10),
isLoading
? const Center(child: Loader())
: CustomOutlinedButton(
text: s.back_to_chat,
height: 52,
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700),
buttonStyle:
ButtonStyle(side: const WidgetStatePropertyAll(BorderSide.none), backgroundColor: WidgetStatePropertyAll(appTheme.blueA400)),
buttonStyle: ButtonStyle(
side: const WidgetStatePropertyAll(BorderSide.none),
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
),
onPressed: () {
GoRouter.of(context).pop();
},
)
),
]
: [
SizedBox(
width: size.width * 0.6,
child: Text(
s.smth_went_wrong_payment_failed,
style: TextStyles.textLSemibold.copyWith(color: appTheme.black),
),
),
const SizedBox(
height: 8,
child: Text(s.smth_went_wrong_payment_failed, style: TextStyles.textLSemibold.copyWith(color: appTheme.black)),
),
const SizedBox(height: 8),
SizedBox(
width: size.width * 0.6,
child: Text(
s.try_again_2,
style: TextStyles.textMMediumAuto.copyWith(color: appTheme.black),
),
),
const SizedBox(
height: 16,
child: Text(s.try_again_2, style: TextStyles.textMMediumAuto.copyWith(color: appTheme.black)),
),
const SizedBox(height: 16),
isLoading
? const Center(child: Loader())
: CustomOutlinedButton(
text: s.pay,
height: 52,
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700),
buttonStyle:
ButtonStyle(side: const WidgetStatePropertyAll(BorderSide.none), backgroundColor: WidgetStatePropertyAll(appTheme.blueA400)),
buttonStyle: ButtonStyle(
side: const WidgetStatePropertyAll(BorderSide.none),
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
),
onPressed: () async {
final planId = context.read<OrderInfoCubit>().state.chosenPlan?.id;
setState(() {
@@ -133,16 +118,15 @@ class _PaymentBannerState extends State<PaymentBanner> {
});
if (paymentLink != null && planId != null) {
if (!context.mounted) return;
GoRouter.of(context).pushReplacement(
PaymentScreen.path,
extra: {'url': paymentLink, 'planId': planId},
);
GoRouter.of(context).pushReplacement(PaymentScreen.path, extra: {'url': paymentLink, 'planId': planId});
}
},
)
),
],
),
)
]));
),
],
),
);
}
}

View File

@@ -49,8 +49,7 @@ class _UserDetailsContentState extends State<UserDetailsContent> {
final List<String> chipsIntervalList = ['1', '3', '6', '12', 'all'];
List<WeightModel> weightPoints = [];
List<CircumferenceModel> circumferencePoints = [];
int _selectedChipIndex = 0;
List<CircumferenceModel> circumferencePoints = []; int _selectedChipIndex = 0;
int _selectedIntervalChipIndex = 0;
bool isMoreOptionsVisible = false;
@override

View File

@@ -1,6 +1,6 @@
name: eatvio_app
description: A new Flutter project.
version: 1.3.4+83
version: 1.3.3+83
publish_to: 'none'
environment:

BIN
test/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,404 @@
import 'package:eatvio_app/core/models/pagination_model.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_settings_model.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart';
import 'package:eatvio_app/features/feed/repositories/feed_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'feed_cubit_test.mocks.dart';
@GenerateNiceMocks([MockSpec<FeedRepository>()])
void main() {
group('FeedCubit', () {
FeedCubit? feedCubit;
late MockFeedRepository mockFeedRepository;
final testBlogPost = FeedBlogPostModel(
id: 1,
title: 'Test Post',
description: 'Test description',
image: 'https://example.com/image.jpg',
state: 'published',
author: const Author(authorSlug: 'author-1', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false),
videoUrl: 'https://example.com/video.mp4',
createdAt: DateTime(2024, 1, 15),
updatedAt: DateTime(2024, 1, 15),
totalLikes: 10,
totalViews: 100,
totalComments: 5,
wasLikedByMe: false,
);
final testBlogPost2 = FeedBlogPostModel(
id: 2,
title: 'Test Post 2',
description: 'Test description 2',
image: 'https://example.com/image2.jpg',
state: 'published',
author: const Author(authorSlug: 'author-2', authorName: 'Author Name 2', authorProfileIcon: 'https://example.com/icon2.jpg', authorIsMe: false),
videoUrl: 'https://example.com/video2.mp4',
createdAt: DateTime(2024, 1, 16),
updatedAt: DateTime(2024, 1, 16),
totalLikes: 20,
totalViews: 200,
totalComments: 10,
wasLikedByMe: true,
);
setUp(() {
mockFeedRepository = MockFeedRepository();
});
tearDown(() async {
if (feedCubit != null && !feedCubit!.isClosed) {
await Future.delayed(const Duration(milliseconds: 100));
feedCubit!.close();
feedCubit = null;
}
});
test('начальное состояние - loading', () {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
expect(feedCubit!.state, const FeedState.loading());
});
test('loadFeedBlogPostList - успешно загружает список постов', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final expectedSettings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost],
meta: const Meta(currentPage: 1, lastPage: 3, total: 3, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer((_) async => expectedSettings);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
expect(feedCubit!.state, isA<FeedStateLoaded>());
final loadedState = feedCubit!.state as FeedStateLoaded;
expect(loadedState.feedBlogPostList.length, 1);
expect(loadedState.feedBlogPostList.first.id, 1);
expect(loadedState.isLoading, false);
expect(feedCubit!.lastPage, 3);
verify(mockFeedRepository.getFeedBlogPosts(query: null)).called(1);
});
test('loadFeedBlogPostList - загружает список постов с query', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
const query = 'test query';
final expectedSettings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost, testBlogPost2],
meta: const Meta(currentPage: 1, lastPage: 1, total: 2, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: query)).thenAnswer((_) async => expectedSettings);
await feedCubit!.loadFeedBlogPostList(query: query);
await Future.delayed(const Duration(milliseconds: 100));
expect(feedCubit!.state, isA<FeedStateLoaded>());
final loadedState = feedCubit!.state as FeedStateLoaded;
expect(loadedState.feedBlogPostList.length, 2);
verify(mockFeedRepository.getFeedBlogPosts(query: query)).called(1);
});
test('loadFeedBlogPostList - обрабатывает ошибку', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final exception = Exception('Network error');
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenThrow(exception);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
expect(feedCubit!.state, isA<FeedStateError>());
final errorState = feedCubit!.state as FeedStateError;
expect(errorState.errorMessage, contains('Exception: Network error'));
});
test('loadNextPage - загружает следующую страницу', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final firstPageSettings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost],
meta: const Meta(currentPage: 1, lastPage: 3, total: 3, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
final secondPageSettings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost2],
meta: const Meta(currentPage: 2, lastPage: 3, total: 3, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer((_) async => firstPageSettings);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
when(mockFeedRepository.getFeedBlogPosts(page: 2, query: null)).thenAnswer((_) async => secondPageSettings);
await feedCubit!.loadNextPage();
await Future.delayed(const Duration(milliseconds: 100));
expect(feedCubit!.state, isA<FeedStateLoaded>());
final loadedState = feedCubit!.state as FeedStateLoaded;
expect(loadedState.feedBlogPostList.length, 2);
expect(feedCubit!.currentPage, 2);
expect(loadedState.isLoading, false);
verify(mockFeedRepository.getFeedBlogPosts(page: 2, query: null)).called(1);
});
test('loadNextPage - не загружает если уже на последней странице', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final settings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost],
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer((_) async => settings);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
await feedCubit!.loadNextPage();
await Future.delayed(const Duration(milliseconds: 100));
verifyNever(mockFeedRepository.getFeedBlogPosts(page: 2, query: anyNamed('query')));
});
test('loadNextPage - не загружает если уже загружается', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final settings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost],
meta: const Meta(currentPage: 1, lastPage: 3, total: 3, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer((_) async => settings);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
feedCubit!.isLoading = true;
await feedCubit!.loadNextPage();
await Future.delayed(const Duration(milliseconds: 100));
verifyNever(mockFeedRepository.getFeedBlogPosts(page: 2, query: anyNamed('query')));
});
test('loadNextPage - обрабатывает ошибку при загрузке следующей страницы', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final firstPageSettings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost],
meta: const Meta(currentPage: 1, lastPage: 3, total: 3, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer((_) async => firstPageSettings);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
final exception = Exception('Network error');
when(mockFeedRepository.getFeedBlogPosts(page: 2, query: null)).thenThrow(exception);
await feedCubit!.loadNextPage();
await Future.delayed(const Duration(milliseconds: 100));
expect(feedCubit!.state, isA<FeedStateError>());
final errorState = feedCubit!.state as FeedStateError;
expect(errorState.errorMessage, contains('Exception: Network error'));
});
test('loadNextPage - сохраняет query при загрузке следующей страницы', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
const query = 'test query';
final firstPageSettings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost],
meta: const Meta(currentPage: 1, lastPage: 3, total: 3, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
final secondPageSettings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost2],
meta: const Meta(currentPage: 2, lastPage: 3, total: 3, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: query)).thenAnswer((_) async => firstPageSettings);
await feedCubit!.loadFeedBlogPostList(query: query);
await Future.delayed(const Duration(milliseconds: 100));
when(mockFeedRepository.getFeedBlogPosts(page: 2, query: query)).thenAnswer((_) async => secondPageSettings);
await feedCubit!.loadNextPage();
await Future.delayed(const Duration(milliseconds: 100));
verify(mockFeedRepository.getFeedBlogPosts(page: 2, query: query)).called(1);
});
test('updateFeedBlogPostList - обновляет лайк поста', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final settings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost],
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer((_) async => settings);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
feedCubit!.updateFeedBlogPostList(testBlogPost, true);
await Future.delayed(const Duration(milliseconds: 100));
expect(feedCubit!.state, isA<FeedStateLoaded>());
final loadedState = feedCubit!.state as FeedStateLoaded;
expect(loadedState.feedBlogPostList.first.wasLikedByMe, true);
expect(loadedState.feedBlogPostList.first.totalLikes, 11);
});
test('updateFeedBlogPostList - убирает лайк поста', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final settings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost2],
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer((_) async => settings);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
feedCubit!.updateFeedBlogPostList(testBlogPost2, false);
await Future.delayed(const Duration(milliseconds: 100));
expect(feedCubit!.state, isA<FeedStateLoaded>());
final loadedState = feedCubit!.state as FeedStateLoaded;
expect(loadedState.feedBlogPostList.first.wasLikedByMe, false);
expect(loadedState.feedBlogPostList.first.totalLikes, 19);
});
test('updateFeedBlogPostList - не обновляет если пост не найден', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final settings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost],
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer((_) async => settings);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
final nonExistentPost = testBlogPost.copyWith(id: 999);
final initialState = feedCubit!.state;
feedCubit!.updateFeedBlogPostList(nonExistentPost, true);
await Future.delayed(const Duration(milliseconds: 100));
expect(feedCubit!.state, initialState);
});
test('updateFeedBlogPostList - не обновляет если state не loaded', () {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
feedCubit!.updateFeedBlogPostList(testBlogPost, true);
expect(feedCubit!.state, const FeedState.loading());
});
test('updateFeedBlogPostList - не обновляет если post null', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
final settings = FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost],
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer((_) async => settings);
await feedCubit!.loadFeedBlogPostList();
await Future.delayed(const Duration(milliseconds: 100));
final initialState = feedCubit!.state;
feedCubit!.updateFeedBlogPostList(null, true);
await Future.delayed(const Duration(milliseconds: 100));
expect(feedCubit!.state, initialState);
});
test('likePost - лайкает пост', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
const postId = 1;
when(mockFeedRepository.likeBlogPost(id: postId)).thenAnswer((_) async => Future.value());
await feedCubit!.likePost(postId);
verify(mockFeedRepository.likeBlogPost(id: postId)).called(1);
});
test('likePost - обрабатывает ошибку без выбрасывания', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
const postId = 1;
final exception = Exception('Network error');
when(mockFeedRepository.likeBlogPost(id: postId)).thenThrow(exception);
await feedCubit!.likePost(postId);
verify(mockFeedRepository.likeBlogPost(id: postId)).called(1);
});
test('unlikedPost - убирает лайк с поста', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
const postId = 1;
when(mockFeedRepository.unlikedBlogPost(id: postId)).thenAnswer((_) async => Future.value());
await feedCubit!.unlikedPost(postId);
verify(mockFeedRepository.unlikedBlogPost(id: postId)).called(1);
});
test('viewPost - отправляет просмотр поста', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
const postId = 1;
when(mockFeedRepository.viewPost(postId)).thenAnswer((_) async => Future.value());
await feedCubit!.viewPost(postId);
verify(mockFeedRepository.viewPost(postId)).called(1);
});
test('viewRecipe - отправляет просмотр рецепта', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
const slug = 'recipe-1';
when(mockFeedRepository.viewRecipe(slug)).thenAnswer((_) async => Future.value());
await feedCubit!.viewRecipe(slug);
verify(mockFeedRepository.viewRecipe(slug)).called(1);
});
test('viewDiet - отправляет просмотр диеты', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
const dietId = 2;
when(mockFeedRepository.viewDiet(dietId)).thenAnswer((_) async => Future.value());
await feedCubit!.viewDiet(dietId);
verify(mockFeedRepository.viewDiet(dietId)).called(1);
});
test('viewPlan - отправляет просмотр плана', () async {
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
const slug = 'plan-1';
when(mockFeedRepository.viewPlan(slug)).thenAnswer((_) async => Future.value());
await feedCubit!.viewPlan(slug);
verify(mockFeedRepository.viewPlan(slug)).called(1);
});
});
}

View File

@@ -0,0 +1,520 @@
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_initializer.dart';
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/core/routing/route_constants.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_settings_model.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart';
import 'package:eatvio_app/features/feed/presentation/widgets/blog_posts.dart';
import 'package:eatvio_app/features/feed/presentation/widgets/chip_group.dart';
import 'package:eatvio_app/features/feed/repositories/feed_repository.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'basic_widget_test.mocks.dart';
@GenerateNiceMocks([MockSpec<FeedRepository>()])
void main() {
group('Feed Basic Widget Tests', () {
late MockFeedRepository mockFeedRepository;
late FeedCubit feedCubit;
final testBlogPost = FeedBlogPostModel(
id: 1,
title: 'Test Post',
description: 'Test description',
image: 'base64image', // Empty to avoid network calls in tests
state: 'published',
author: const Author(authorSlug: 'author-1', authorName: 'Author Name', authorProfileIcon: '', authorIsMe: false),
videoUrl: '',
createdAt: DateTime(2024, 1, 15),
updatedAt: DateTime(2024, 1, 15),
totalLikes: 10,
totalViews: 100,
totalComments: 5,
wasLikedByMe: false,
);
final testBlogPost2 = FeedBlogPostModel(
id: 2,
title: 'Test Post 2',
description: 'Test description 2',
image: 'base64image', // Empty to avoid network calls in tests
state: 'published',
author: const Author(authorSlug: 'author-2', authorName: 'Author Name 2', authorProfileIcon: '', authorIsMe: false),
videoUrl: '',
createdAt: DateTime(2024, 1, 16),
updatedAt: DateTime(2024, 1, 16),
totalLikes: 20,
totalViews: 200,
totalComments: 10,
wasLikedByMe: true,
);
setUp(() async {
await sl.reset();
dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost');
mockFeedRepository = MockFeedRepository();
feedCubit = FeedCubit(feedRepository: mockFeedRepository);
// Register AppConfig with proper baseUrl for image URL construction
sl.registerLazySingleton<AppConfig>(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost'));
});
tearDown(() async {
await Future.delayed(const Duration(milliseconds: 100));
if (!feedCubit.isClosed) {
feedCubit.close();
}
});
Widget createTestWidget(Widget child, {bool wrapInScaffold = true}) {
final widget = BlocProvider<FeedCubit>(
create: (context) => feedCubit,
child: wrapInScaffold ? Scaffold(body: SingleChildScrollView(child: child)) : SizedBox(width: 800, height: 600, child: child),
);
return MaterialApp(
theme: ThemeHelper().themeData(),
localizationsDelegates: const [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('ru')],
home: widget,
);
}
Widget createBlogPostsTestWidget(Widget child) {
// Create a minimal GoRouter for tests
final router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => BlocProvider<FeedCubit>(
create: (context) => feedCubit,
child: Scaffold(
body: LayoutBuilder(
builder: (context, constraints) => SizedBox(
width: constraints.maxWidth > 0 ? constraints.maxWidth : 800,
height: constraints.maxHeight > 0 ? constraints.maxHeight : 600,
child: child,
),
),
),
),
),
GoRoute(
path: RouteConstants.blogPostScreen,
name: 'blogPostScreen',
builder: (context, state) => Scaffold(
appBar: AppBar(title: const Text('Blog Post')),
body: Center(child: Text('Blog Post ${state.extra ?? ''}')),
),
),
],
);
return MaterialApp.router(
theme: ThemeHelper().themeData(),
routerConfig: router,
localizationsDelegates: const [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('ru')],
);
}
testWidgets('should create FeedCubit successfully', (WidgetTester tester) async {
// Arrange & Act
final cubit = FeedCubit(feedRepository: mockFeedRepository);
// Assert
expect(cubit, isA<FeedCubit>());
expect(cubit.state, const FeedState.loading());
cubit.close();
});
testWidgets('should display ChipGroup with all chips', (WidgetTester tester) async {
// Arrange
final chipsLabelList = ['Все', 'Рецепты', 'Диеты', 'Планы питания', 'Консультанты'];
int selectedIndex = 0;
final widget = ChipGroup(
selectedChipIndex: selectedIndex,
chipsLabelList: chipsLabelList,
setSelectedChipIndex: (index) {
selectedIndex = index;
},
);
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pumpAndSettle();
// Assert
expect(find.text('Все'), findsOneWidget);
expect(find.text('Рецепты'), findsOneWidget);
expect(find.text('Диеты'), findsOneWidget);
expect(find.text('Планы питания'), findsOneWidget);
expect(find.text('Консультанты'), findsOneWidget);
});
testWidgets('should handle chip selection in ChipGroup', (WidgetTester tester) async {
// Arrange
final chipsLabelList = ['Все', 'Рецепты', 'Диеты'];
int selectedIndex = 0;
final widget = ChipGroup(
selectedChipIndex: selectedIndex,
chipsLabelList: chipsLabelList,
setSelectedChipIndex: (index) {
selectedIndex = index;
},
);
await tester.pumpWidget(createTestWidget(widget));
await tester.pumpAndSettle();
// Act
await tester.tap(find.text('Рецепты'));
await tester.pump();
// Assert
expect(selectedIndex, 1);
});
testWidgets('should display ChipGroup with custom labels', (WidgetTester tester) async {
// Arrange
final chipsLabelList = ['Tab 1', 'Tab 2', 'Tab 3'];
final widget = ChipGroup(selectedChipIndex: 0, chipsLabelList: chipsLabelList, setSelectedChipIndex: (index) {});
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pumpAndSettle();
// Assert
expect(find.text('Tab 1'), findsOneWidget);
expect(find.text('Tab 2'), findsOneWidget);
expect(find.text('Tab 3'), findsOneWidget);
});
testWidgets('should display BlogPosts widget with loading state', (WidgetTester tester) async {
// Arrange
feedCubit.emit(const FeedState.loading());
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
// Act
final router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => BlocProvider<FeedCubit>(create: (context) => feedCubit, child: widget),
),
],
);
await tester.pumpWidget(
MaterialApp.router(
theme: ThemeHelper().themeData(),
routerConfig: router,
localizationsDelegates: const [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('ru')],
),
);
await tester.pump();
// Assert
expect(feedCubit.state, isA<FeedStateLoading>());
expect(find.byType(BlogPosts), findsOneWidget);
});
testWidgets('should display BlogPosts widget with loaded state', (WidgetTester tester) async {
// Arrange
feedCubit.emit(FeedState.loaded(feedBlogPostList: [testBlogPost, testBlogPost2], isLoading: false));
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
// Act
await tester.pumpWidget(createBlogPostsTestWidget(widget));
// Use pump() multiple times to allow error widgets to render without waiting for network
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
await tester.pump(const Duration(milliseconds: 50));
// Assert - Verify state and widget structure
expect(feedCubit.state, isA<FeedStateLoaded>());
final loadedState = feedCubit.state as FeedStateLoaded;
expect(loadedState.feedBlogPostList.length, 2);
expect(find.byType(BlogPosts), findsOneWidget);
expect(find.byType(RefreshIndicator), findsOneWidget);
// ListView should be present in loaded state
expect(find.byType(ListView), findsOneWidget);
});
testWidgets('should display BlogPosts widget with error state', (WidgetTester tester) async {
// Arrange
feedCubit.emit(const FeedState.error(errorMessage: 'Ошибка загрузки постов'));
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
// Act
await tester.pumpWidget(createBlogPostsTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Assert
expect(feedCubit.state, isA<FeedStateError>());
final errorState = feedCubit.state as FeedStateError;
expect(errorState.errorMessage, 'Ошибка загрузки постов');
expect(find.byType(BlogPosts), findsOneWidget);
});
testWidgets('should display BlogPosts with empty list', (WidgetTester tester) async {
// Arrange
feedCubit.emit(const FeedState.loaded(feedBlogPostList: [], isLoading: false));
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
// Act
await tester.pumpWidget(createBlogPostsTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Assert
expect(feedCubit.state, isA<FeedStateLoaded>());
final loadedState = feedCubit.state as FeedStateLoaded;
expect(loadedState.feedBlogPostList.isEmpty, true);
expect(find.byType(BlogPosts), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
});
testWidgets('should display BlogPosts with loading indicator when isLoading is true', (WidgetTester tester) async {
// Arrange
feedCubit.emit(FeedState.loaded(feedBlogPostList: [testBlogPost], isLoading: true));
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
// Act
await tester.pumpWidget(createBlogPostsTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Assert
expect(feedCubit.state, isA<FeedStateLoaded>());
final loadedState = feedCubit.state as FeedStateLoaded;
expect(loadedState.isLoading, true);
expect(find.byType(BlogPosts), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
});
testWidgets('should handle chip selection with multiple chips', (WidgetTester tester) async {
// Arrange
final chipsLabelList = ['Все', 'Рецепты', 'Диеты', 'Планы питания', 'Консультанты'];
int selectedIndex = 0;
final widget = ChipGroup(
selectedChipIndex: selectedIndex,
chipsLabelList: chipsLabelList,
setSelectedChipIndex: (index) {
selectedIndex = index;
},
);
await tester.pumpWidget(createTestWidget(widget));
await tester.pumpAndSettle();
// Act
await tester.tap(find.text('Диеты'));
await tester.pump();
// Assert
expect(selectedIndex, 2);
});
testWidgets('should display ChipGroup with single chip', (WidgetTester tester) async {
// Arrange
final chipsLabelList = ['Все'];
final widget = ChipGroup(selectedChipIndex: 0, chipsLabelList: chipsLabelList, setSelectedChipIndex: (index) {});
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pumpAndSettle();
// Assert
expect(find.text('Все'), findsOneWidget);
});
testWidgets('should handle BlogPosts refresh', (WidgetTester tester) async {
// Arrange
feedCubit.emit(FeedState.loaded(feedBlogPostList: [testBlogPost], isLoading: false));
when(mockFeedRepository.getFeedBlogPosts(query: null)).thenAnswer(
(_) async => FeedBlogPostSettingsModel(
feedBlogPostList: [testBlogPost, testBlogPost2],
meta: const Meta(currentPage: 1, lastPage: 1, total: 2, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
),
);
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
await tester.pumpWidget(createBlogPostsTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Act - Verify refresh indicator exists
expect(find.byType(RefreshIndicator), findsOneWidget);
// Assert
expect(feedCubit.state, isA<FeedStateLoaded>());
expect(find.byType(ListView), findsOneWidget);
});
testWidgets('should display ChipGroup with correct selected chip', (WidgetTester tester) async {
// Arrange
final chipsLabelList = ['Все', 'Рецепты', 'Диеты'];
final widget = ChipGroup(selectedChipIndex: 1, chipsLabelList: chipsLabelList, setSelectedChipIndex: (index) {});
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pumpAndSettle();
// Assert
expect(find.text('Рецепты'), findsOneWidget);
expect(find.text('Все'), findsOneWidget);
expect(find.text('Диеты'), findsOneWidget);
});
testWidgets('should handle BlogPosts visibility detection', (WidgetTester tester) async {
// Arrange
feedCubit.emit(FeedState.loaded(feedBlogPostList: [testBlogPost], isLoading: false));
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
// Act
await tester.pumpWidget(createBlogPostsTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Assert
expect(find.byType(BlogPosts), findsOneWidget);
expect(find.byType(RefreshIndicator), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
// Visibility detection is handled by VisibilityDetector internally
});
testWidgets('should display BlogPosts with multiple posts', (WidgetTester tester) async {
// Arrange
feedCubit.emit(FeedState.loaded(feedBlogPostList: [testBlogPost, testBlogPost2], isLoading: false));
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
// Act
await tester.pumpWidget(createBlogPostsTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Assert
expect(feedCubit.state, isA<FeedStateLoaded>());
final loadedState = feedCubit.state as FeedStateLoaded;
expect(loadedState.feedBlogPostList.length, 2);
expect(find.byType(BlogPosts), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
});
testWidgets('should handle ChipGroup with empty label list', (WidgetTester tester) async {
// Arrange
final chipsLabelList = <String>[];
final widget = ChipGroup(selectedChipIndex: 0, chipsLabelList: chipsLabelList, setSelectedChipIndex: (index) {});
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pumpAndSettle();
// Assert
expect(find.byType(ChipGroup), findsOneWidget);
});
testWidgets('should display BlogPosts structure correctly', (WidgetTester tester) async {
// Arrange
feedCubit.emit(FeedState.loaded(feedBlogPostList: [testBlogPost], isLoading: false));
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
// Act
await tester.pumpWidget(createBlogPostsTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Assert
expect(find.byType(BlogPosts), findsOneWidget);
expect(find.byType(RefreshIndicator), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
expect(feedCubit.state, isA<FeedStateLoaded>());
});
testWidgets('should handle chip selection callback', (WidgetTester tester) async {
// Arrange
final chipsLabelList = ['Все', 'Рецепты'];
int callbackIndex = -1;
final widget = ChipGroup(
selectedChipIndex: 0,
chipsLabelList: chipsLabelList,
setSelectedChipIndex: (index) {
callbackIndex = index;
},
);
await tester.pumpWidget(createTestWidget(widget));
await tester.pumpAndSettle();
// Act
await tester.tap(find.text('Рецепты'));
await tester.pump();
// Assert
expect(callbackIndex, 1);
});
testWidgets('should display BlogPosts with scrollable list', (WidgetTester tester) async {
// Arrange
final posts = List.generate(10, (index) => testBlogPost.copyWith(id: index + 1));
feedCubit.emit(FeedState.loaded(feedBlogPostList: posts, isLoading: false));
final widget = BlogPosts(handleVisibility: ({required visibleFraction, required id, required type}) {});
// Act
await tester.pumpWidget(createBlogPostsTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Assert
expect(find.byType(BlogPosts), findsOneWidget);
expect(find.byType(RefreshIndicator), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
expect(feedCubit.state, isA<FeedStateLoaded>());
final loadedState = feedCubit.state as FeedStateLoaded;
expect(loadedState.feedBlogPostList.length, 10);
});
});
}

View File

@@ -0,0 +1,609 @@
import 'package:eatvio_app/core/models/pagination_model.dart';
import 'package:eatvio_app/features/feed/models/comment_model.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_settings_model.dart';
import 'package:eatvio_app/features/feed/models/feed_consultant_model.dart';
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/recipes_model.dart';
import 'package:eatvio_app/features/feed/models/recipes_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/view_model.dart';
import 'package:eatvio_app/features/feed/repositories/feed_repository.dart';
import 'package:eatvio_app/features/feed/services/feed_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'feed_repository_test.mocks.dart';
@GenerateNiceMocks([MockSpec<FeedService>()])
void main() {
group('FeedRepository', () {
late FeedRepository feedRepository;
late MockFeedService mockFeedService;
setUp(() {
mockFeedService = MockFeedService();
feedRepository = FeedRepository(feedService: mockFeedService);
});
test('getFeedBlogPosts - возвращает список постов блога', () async {
const page = 1;
const query = 'test query';
final expectedSettings = FeedBlogPostSettingsModel(
feedBlogPostList: [
FeedBlogPostModel(
id: 1,
title: 'Test Post',
description: 'Test description',
image: 'https://example.com/image.jpg',
state: 'published',
author: const Author(authorSlug: 'author-1', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false),
videoUrl: 'https://example.com/video.mp4',
createdAt: DateTime(2024, 1, 15),
updatedAt: DateTime(2024, 1, 15),
totalLikes: 10,
totalViews: 100,
totalComments: 5,
wasLikedByMe: false,
),
],
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getBlogPostList(page: page, query: query)).thenAnswer((_) async => expectedSettings);
final result = await feedRepository.getFeedBlogPosts(query: query, page: page);
expect(result, isA<FeedBlogPostSettingsModel>());
expect(result.feedBlogPostList.length, 1);
expect(result.feedBlogPostList.first.id, 1);
verify(mockFeedService.getBlogPostList(page: page, query: query)).called(1);
});
test('getFeedBlogPosts - возвращает список постов без query', () async {
const page = 1;
const expectedSettings = FeedBlogPostSettingsModel(
feedBlogPostList: [],
meta: Meta(currentPage: 1, lastPage: 1, total: 0, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getBlogPostList(page: page, query: null)).thenAnswer((_) async => expectedSettings);
final result = await feedRepository.getFeedBlogPosts(page: page);
expect(result, isA<FeedBlogPostSettingsModel>());
expect(result.feedBlogPostList.isEmpty, true);
verify(mockFeedService.getBlogPostList(page: page, query: null)).called(1);
});
test('getBlogPost - возвращает пост блога по ID', () async {
const id = 1;
final expectedPost = FeedBlogPostModel(
id: id,
title: 'Test Post',
description: 'Test description',
image: 'https://example.com/image.jpg',
state: 'published',
author: const Author(authorSlug: 'author-1', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false),
videoUrl: 'https://example.com/video.mp4',
createdAt: DateTime(2024, 1, 15),
updatedAt: DateTime(2024, 1, 15),
totalLikes: 10,
totalViews: 100,
totalComments: 5,
wasLikedByMe: false,
);
when(mockFeedService.getBlogPost(postId: id)).thenAnswer((_) async => expectedPost);
final result = await feedRepository.getBlogPost(id: id);
expect(result, isA<FeedBlogPostModel>());
expect(result.id, id);
verify(mockFeedService.getBlogPost(postId: id)).called(1);
});
test('getRecipes - возвращает список рецептов', () async {
const page = 1;
const query = 'pasta';
final tags = [1, 2, 3];
final expectedRecipes = [
Recipe(
id: 1,
image: 'https://example.com/recipe.jpg',
state: 'published',
cookingTime: 30,
activeCookingTime: 20,
ingredients: [const Ingredient(name: 'Pasta', unit: 'g', portion: '200g', productId: 1)],
description: 'Test recipe description',
steps: [const Step(description: 'Step 1', image: 'https://example.com/step1.jpg')],
videoUrl: 'https://example.com/video.mp4',
createdAt: DateTime(2024, 1, 15),
updatedAt: DateTime(2024, 1, 15),
title: 'Pasta Recipe',
type: 'recipe',
slug: 'pasta-recipe',
commentsCount: 5,
wasLikedByMe: false,
isFavorite: false,
calories: 350.0,
servings: 4,
likesCount: 20,
viewsCount: 150,
tags: [const Tag(name: 'Italian')],
author: const Author(authorSlug: 'chef-1', authorName: 'Chef Name', authorProfileIcon: 'https://example.com/chef.jpg', authorIsMe: false),
),
];
final expectedPagination = RecipesPagination(recipesList: expectedRecipes);
when(mockFeedService.getRecipes(query: query, tags: tags, page: page)).thenAnswer((_) async => expectedPagination);
final result = await feedRepository.getRecipes(query: query, tags: tags, page: page);
expect(result, isA<List<Recipe>>());
expect(result.length, 1);
expect(result.first.id, 1);
verify(mockFeedService.getRecipes(query: query, tags: tags, page: page)).called(1);
});
test('getRecipes - возвращает список рецептов без query и tags', () async {
const page = 1;
final expectedRecipes = <Recipe>[];
final expectedPagination = RecipesPagination(recipesList: expectedRecipes);
when(mockFeedService.getRecipes(query: null, tags: null, page: page)).thenAnswer((_) async => expectedPagination);
final result = await feedRepository.getRecipes(page: page);
expect(result, isA<List<Recipe>>());
expect(result.isEmpty, true);
verify(mockFeedService.getRecipes(query: null, tags: null, page: page)).called(1);
});
test('getDiets - возвращает список диет', () async {
const page = 1;
const query = 'keto';
const types = 'keto';
const duration = 30;
const sorting = 'popular';
const expectedDiets = DietsPagination(
data: [
Diet(
id: 1,
slug: 'keto-diet',
name: 'Keto Diet',
image: 'https://example.com/keto.jpg',
duration: duration,
state: DietState.active,
type: DietType(light: false, veg: false, carb: false, meat: true),
details: 'Keto diet description',
dailySchedule: {},
author: Author(
authorSlug: 'nutritionist-1',
authorName: 'Nutritionist Name',
authorProfileIcon: 'https://example.com/nutritionist.jpg',
authorIsMe: false,
),
totalLikes: 50,
totalViews: 500,
totalComments: 25,
wasLikedByMe: false,
isFavorite: false,
dailyNutrition: [],
),
],
links: Links(first: '', last: '', prev: null, next: null),
meta: Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getDiets(page: page, query: query, types: types, duration: duration, sorting: sorting)).thenAnswer((_) async => expectedDiets);
final result = await feedRepository.getDiets(page: page, query: query, types: types, duration: duration, sorting: sorting);
expect(result, isA<DietsPagination>());
expect(result.data.length, 1);
expect(result.data.first.id, 1);
verify(mockFeedService.getDiets(page: page, query: query, types: types, duration: duration, sorting: sorting)).called(1);
});
test('getDiets - возвращает список диет без параметров', () async {
const page = 1;
const expectedDiets = DietsPagination(
data: [],
links: Links(first: '', last: '', prev: null, next: null),
meta: Meta(currentPage: 1, lastPage: 1, total: 0, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getDiets(page: page, query: null, types: null, duration: null, sorting: null)).thenAnswer((_) async => expectedDiets);
final result = await feedRepository.getDiets(page: page);
expect(result, isA<DietsPagination>());
expect(result.data.isEmpty, true);
verify(mockFeedService.getDiets(page: page, query: null, types: null, duration: null, sorting: null)).called(1);
});
test('getPlans - возвращает список планов', () async {
const page = 1;
const query = 'weight loss';
const types = 'slim';
const duration = 30;
const minPrice = 1000;
const maxPrice = 5000;
final expectedPlans = PlanPaginationModel(
data: [
PlanModel(
id: 1,
slug: 'weight-loss-plan',
name: 'Weight Loss Plan',
image: 'https://example.com/plan.jpg',
duration: duration,
state: 'active',
type: const PlanType(fit: false, slim: true, behavior: false, wellness: false),
details: 'Weight loss plan description',
packetsCount: 30,
author: const Author(
authorSlug: 'consultant-1',
authorName: 'Consultant Name',
authorProfileIcon: 'https://example.com/consultant.jpg',
authorIsMe: false,
),
totalLikes: 100,
totalViews: 1000,
totalComments: 50,
isFavorite: false,
minPriceOfOptions: minPrice.toDouble(),
maxPriceOfOptions: maxPrice.toDouble(),
wasLikedByMe: false,
),
],
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(
mockFeedService.getPlans(page: page, query: query, types: types, duration: duration, minPrice: minPrice, maxPrice: maxPrice),
).thenAnswer((_) async => expectedPlans);
final result = await feedRepository.getPlans(page: page, query: query, types: types, duration: duration, minPrice: minPrice, maxPrice: maxPrice);
expect(result, isA<PlanPaginationModel>());
expect(result.data.length, 1);
expect(result.data.first.id, 1);
verify(mockFeedService.getPlans(page: page, query: query, types: types, duration: duration, minPrice: minPrice, maxPrice: maxPrice)).called(1);
});
test('getPlans - возвращает список планов без параметров', () async {
const page = 1;
const expectedPlans = PlanPaginationModel(
data: [],
links: Links(first: '', last: '', prev: null, next: null),
meta: Meta(currentPage: 1, lastPage: 1, total: 0, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(
mockFeedService.getPlans(page: page, query: null, types: null, duration: null, minPrice: null, maxPrice: null),
).thenAnswer((_) async => expectedPlans);
final result = await feedRepository.getPlans(page: page);
expect(result, isA<PlanPaginationModel>());
expect(result.data.isEmpty, true);
verify(mockFeedService.getPlans(page: page, query: null, types: null, duration: null, minPrice: null, maxPrice: null)).called(1);
});
test('getBlogPostComments - возвращает комментарии поста блога', () async {
const id = '1';
final expectedComments = CommentModel(
data: [
Comment(
id: 1,
authorName: 'User 1',
authorSlug: 'user-1',
authorProfileIcon: 'https://example.com/user1.jpg',
body: 'Great post!',
childrenComments: [],
createdAt: DateTime(2024, 1, 15),
),
],
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getBlogPostComments(id: id)).thenAnswer((_) async => expectedComments);
final result = await feedRepository.getBlogPostComments(id: id);
expect(result, isA<CommentModel>());
expect(result.data.length, 1);
expect(result.data.first.id, 1);
verify(mockFeedService.getBlogPostComments(id: id)).called(1);
});
test('sendBlogPostComment - отправляет комментарий к посту блога', () async {
const id = '1';
const commentText = 'Nice post!';
const parentCommentId = 5;
when(mockFeedService.sendBlogPostComment(id: id, body: commentText, parentCommentId: parentCommentId)).thenAnswer((_) async => Future.value());
await feedRepository.sendBlogPostComment(id: id, commentText: commentText, parentCommentId: parentCommentId);
verify(mockFeedService.sendBlogPostComment(id: id, body: commentText, parentCommentId: parentCommentId)).called(1);
});
test('sendBlogPostComment - отправляет комментарий без parentCommentId', () async {
const id = '1';
const commentText = 'Nice post!';
when(mockFeedService.sendBlogPostComment(id: id, body: commentText, parentCommentId: null)).thenAnswer((_) async => Future.value());
await feedRepository.sendBlogPostComment(id: id, commentText: commentText);
verify(mockFeedService.sendBlogPostComment(id: id, body: commentText, parentCommentId: null)).called(1);
});
test('getDietsComments - возвращает комментарии диеты', () async {
const id = '5';
final expectedComments = CommentModel(
data: [
Comment(
id: 2,
authorName: 'User 2',
authorSlug: 'user-2',
authorProfileIcon: 'https://example.com/user2.jpg',
body: 'Great diet!',
childrenComments: [],
createdAt: DateTime(2024, 1, 15),
),
],
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getDietsComments(id: id)).thenAnswer((_) async => expectedComments);
final result = await feedRepository.getDietsComments(id: id);
expect(result, isA<CommentModel>());
expect(result.data.length, 1);
verify(mockFeedService.getDietsComments(id: id)).called(1);
});
test('sendDietsComment - отправляет комментарий к диете', () async {
const id = '5';
const commentText = 'Nice diet!';
const parentCommentId = 10;
when(mockFeedService.sendDietsComment(id: id, body: commentText, parentCommentId: parentCommentId)).thenAnswer((_) async => Future.value());
await feedRepository.sendDietsComment(id: id, commentText: commentText, parentCommentId: parentCommentId);
verify(mockFeedService.sendDietsComment(id: id, body: commentText, parentCommentId: parentCommentId)).called(1);
});
test('getRecipesComments - возвращает комментарии рецепта', () async {
const id = '33';
final expectedComments = CommentModel(
data: [
Comment(
id: 3,
authorName: 'User 3',
authorSlug: 'user-3',
authorProfileIcon: 'https://example.com/user3.jpg',
body: 'Looks tasty!',
childrenComments: [],
createdAt: DateTime(2024, 1, 15),
),
],
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getRecipesComments(id: id)).thenAnswer((_) async => expectedComments);
final result = await feedRepository.getRecipesComments(id: id);
expect(result, isA<CommentModel>());
expect(result.data.length, 1);
verify(mockFeedService.getRecipesComments(id: id)).called(1);
});
test('sendRecipesComment - отправляет комментарий к рецепту', () async {
const id = '33';
const commentText = 'Tasty recipe!';
const parentCommentId = 15;
when(mockFeedService.sendRecipesComment(id: id, body: commentText, parentCommentId: parentCommentId)).thenAnswer((_) async => Future.value());
await feedRepository.sendRecipesComment(id: id, commentText: commentText, parentCommentId: parentCommentId);
verify(mockFeedService.sendRecipesComment(id: id, body: commentText, parentCommentId: parentCommentId)).called(1);
});
test('getPlansComments - возвращает комментарии плана', () async {
const slug = 'plan-1';
final expectedComments = CommentModel(
data: [
Comment(
id: 4,
authorName: 'User 4',
authorSlug: 'user-4',
authorProfileIcon: 'https://example.com/user4.jpg',
body: 'Super plan!',
childrenComments: [],
createdAt: DateTime(2024, 1, 15),
),
],
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getPlansComments(slug: slug)).thenAnswer((_) async => expectedComments);
final result = await feedRepository.getPlansComments(slug: slug);
expect(result, isA<CommentModel>());
expect(result.data.length, 1);
verify(mockFeedService.getPlansComments(slug: slug)).called(1);
});
test('sendPlansComment - отправляет комментарий к плану', () async {
const slug = 'plan-1';
const commentText = 'Great plan!';
const parentCommentId = 20;
when(mockFeedService.sendPlansComment(slug: slug, body: commentText, parentCommentId: parentCommentId)).thenAnswer((_) async => Future.value());
await feedRepository.sendPlansComment(slug: slug, commentText: commentText, parentCommentId: parentCommentId);
verify(mockFeedService.sendPlansComment(slug: slug, body: commentText, parentCommentId: parentCommentId)).called(1);
});
test('likeBlogPost - лайкает пост блога', () async {
const id = 1;
when(mockFeedService.likeBlogPost(id: id)).thenAnswer((_) async => Future.value());
await feedRepository.likeBlogPost(id: id);
verify(mockFeedService.likeBlogPost(id: id)).called(1);
});
test('unlikedBlogPost - убирает лайк с поста блога', () async {
const id = 1;
when(mockFeedService.unlikedBlogPost(id: id)).thenAnswer((_) async => Future.value());
await feedRepository.unlikedBlogPost(id: id);
verify(mockFeedService.unlikedBlogPost(id: id)).called(1);
});
test('getConsultants - возвращает список консультантов', () async {
const name = 'Anna';
final expectedConsultants = [
const FeedConsultantModel(
slug: 'consultant-1',
name: 'Anna Ivanova',
description: 'Test consultant description',
totalScores: 5,
photo: 'https://example.com/consultant1.jpg',
badges: [],
),
];
final expectedPagination = FeedConsultantPaginationModel(
data: expectedConsultants,
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getConsultants(name: name)).thenAnswer((_) async => expectedPagination);
final result = await feedRepository.getConsultants(name);
expect(result, isA<List<FeedConsultantModel>>());
expect(result.length, 1);
expect(result.first.name, 'Anna Ivanova');
verify(mockFeedService.getConsultants(name: name)).called(1);
});
test('getConsultants - возвращает список консультантов без имени', () async {
final expectedConsultants = <FeedConsultantModel>[];
final expectedPagination = FeedConsultantPaginationModel(
data: expectedConsultants,
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 0, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getConsultants(name: null)).thenAnswer((_) async => expectedPagination);
final result = await feedRepository.getConsultants();
expect(result, isA<List<FeedConsultantModel>>());
expect(result.isEmpty, true);
verify(mockFeedService.getConsultants(name: null)).called(1);
});
test('viewPost - отправляет просмотр поста', () async {
const id = 1;
when(mockFeedService.viewPost(id: id)).thenAnswer((_) async => Future.value());
await feedRepository.viewPost(id);
verify(mockFeedService.viewPost(id: id)).called(1);
});
test('viewRecipe - отправляет просмотр рецепта', () async {
const slug = 'recipe-1';
when(mockFeedService.viewRecipe(slug: slug)).thenAnswer((_) async => Future.value());
await feedRepository.viewRecipe(slug);
verify(mockFeedService.viewRecipe(slug: slug)).called(1);
});
test('viewDiet - отправляет просмотр диеты', () async {
const id = 2;
when(mockFeedService.viewDiet(id: id)).thenAnswer((_) async => Future.value());
await feedRepository.viewDiet(id);
verify(mockFeedService.viewDiet(id: id)).called(1);
});
test('viewPlan - отправляет просмотр плана', () async {
const slug = 'plan-7';
when(mockFeedService.viewPlan(slug: slug)).thenAnswer((_) async => Future.value());
await feedRepository.viewPlan(slug);
verify(mockFeedService.viewPlan(slug: slug)).called(1);
});
test('viewContent - отправляет просмотр контента', () async {
final viewModel = ViewModel(type: 'recipe', slugs: ['recipe-1']);
when(mockFeedService.viewContent(viewModel: viewModel)).thenAnswer((_) async => Future.value());
await feedRepository.viewContent(viewModel: viewModel);
verify(mockFeedService.viewContent(viewModel: viewModel)).called(1);
});
test('viewContent - отправляет просмотр контента с ids', () async {
final viewModel = ViewModel(type: 'diet', ids: [1, 2, 3]);
when(mockFeedService.viewContent(viewModel: viewModel)).thenAnswer((_) async => Future.value());
await feedRepository.viewContent(viewModel: viewModel);
verify(mockFeedService.viewContent(viewModel: viewModel)).called(1);
});
test('getFeedBlogPosts - пробрасывает исключение при ошибке', () async {
const page = 1;
final exception = Exception('Network error');
when(mockFeedService.getBlogPostList(page: page, query: null)).thenThrow(exception);
expect(() => feedRepository.getFeedBlogPosts(page: page), throwsA(isA<Exception>()));
});
test('getBlogPost - пробрасывает исключение при ошибке', () async {
const id = 1;
final exception = Exception('Not found');
when(mockFeedService.getBlogPost(postId: id)).thenThrow(exception);
expect(() => feedRepository.getBlogPost(id: id), throwsA(isA<Exception>()));
});
});
}

View File

@@ -0,0 +1,378 @@
import 'package:eatvio_app/core/models/pagination_model.dart';
import 'package:eatvio_app/features/feed/models/comment_model.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_settings_model.dart';
import 'package:eatvio_app/features/feed/models/feed_consultant_model.dart';
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/recipes_model.dart';
import 'package:eatvio_app/features/feed/models/recipes_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/view_model.dart';
import 'package:eatvio_app/features/feed/services/feed_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'feed_service_test.mocks.dart';
@GenerateNiceMocks([MockSpec<FeedService>()])
void main() {
group('FeedService', () {
late MockFeedService mockFeedService;
setUp(() {
mockFeedService = MockFeedService();
});
test('getBlogPostList returns settings', () async {
const page = 1;
final expected = FeedBlogPostSettingsModel(
feedBlogPostList: [
FeedBlogPostModel(
id: 1,
title: 'Post Title',
description: 'Test post description',
image: 'https://someurl.com/img.jpg',
state: 'published',
author: const Author(authorSlug: '', authorName: '', authorProfileIcon: '', authorIsMe: false),
videoUrl: 'https://someurl.com/video.mp4',
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
totalLikes: 5,
totalViews: 10,
totalComments: 2,
wasLikedByMe: false,
),
],
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getBlogPostList(page: page, query: null)).thenAnswer((_) async => expected);
final result = await mockFeedService.getBlogPostList(page: page, query: null);
expect(result, isA<FeedBlogPostSettingsModel>());
verify(mockFeedService.getBlogPostList(page: page, query: null)).called(1);
});
test('getBlogPost returns post', () async {
const id = 10;
final expected = FeedBlogPostModel(
id: id,
title: 'Test',
description: 'Test post description',
image: 'https://someurl.com/img.jpg',
state: 'published',
author: const Author(authorSlug: '', authorName: '', authorProfileIcon: '', authorIsMe: false),
videoUrl: 'https://someurl.com/video.mp4',
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
totalLikes: 3,
totalViews: 14,
totalComments: 1,
wasLikedByMe: false,
);
when(mockFeedService.getBlogPost(postId: id)).thenAnswer((_) async => expected);
final result = await mockFeedService.getBlogPost(postId: id);
expect(result.id, id);
verify(mockFeedService.getBlogPost(postId: id)).called(1);
});
test('getRecipes returns recipes pagination', () async {
final expected = RecipesPagination(
recipesList: [
Recipe(
id: 1,
image: 'https://someurl.com/img.jpg',
state: 'published',
cookingTime: 30,
activeCookingTime: 20,
ingredients: [const Ingredient(name: 'ingredient1', unit: 'unit1', portion: 'portion1', productId: 1)],
description: 'Test post description',
steps: [const Step(description: 'step1', image: 'https://someurl.com/img.jpg')],
videoUrl: 'https://someurl.com/video.mp4',
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
title: 'Test',
type: 'recipe',
slug: 'test-recipe',
commentsCount: 1,
wasLikedByMe: false,
isFavorite: false,
calories: 100,
servings: 1,
likesCount: 3,
viewsCount: 14,
tags: [const Tag(name: '1')],
author: const Author(authorSlug: '', authorName: '', authorProfileIcon: '', authorIsMe: false),
),
],
);
when(mockFeedService.getRecipes(page: 1, tags: [1], query: null)).thenAnswer((_) async => expected);
await mockFeedService.getRecipes(page: 1, tags: [1], query: null);
verify(mockFeedService.getRecipes(page: 1, tags: [1], query: null)).called(1);
});
test('getDiets returns pagination', () async {
const expected = DietsPagination(
data: [
Diet(
id: 1,
slug: 'test-diet',
name: 'Test Diet',
image: 'https://someurl.com/img.jpg',
duration: 30,
state: DietState.active,
type: DietType(light: false, veg: false, carb: false, meat: false),
details: 'Test diet description',
dailySchedule: {},
author: Author(authorSlug: '', authorName: '', authorProfileIcon: '', authorIsMe: false),
totalLikes: 1,
totalViews: 1,
totalComments: 1,
wasLikedByMe: false,
isFavorite: false,
dailyNutrition: [],
),
],
links: Links(first: '', last: '', prev: null, next: null),
meta: Meta(currentPage: 1, lastPage: 1, total: 0, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getDiets(page: 1, query: null)).thenAnswer((_) async => expected);
await mockFeedService.getDiets(page: 1, query: null);
verify(mockFeedService.getDiets(page: 1, query: null)).called(1);
});
test('getPlans returns pagination', () async {
const expected = PlanPaginationModel(
data: [
PlanModel(
id: 1,
slug: 'test-plan',
name: 'Test Plan',
image: 'https://someurl.com/img.jpg',
duration: 30,
state: 'active',
type: PlanType(fit: false, slim: false, behavior: false, wellness: false),
details: '',
packetsCount: 1,
author: Author(authorSlug: '', authorName: '', authorProfileIcon: '', authorIsMe: false),
totalLikes: 1,
totalViews: 1,
totalComments: 1,
isFavorite: false,
minPriceOfOptions: 100,
maxPriceOfOptions: 500,
wasLikedByMe: false,
),
],
links: Links(first: '', last: '', prev: null, next: null),
meta: Meta(currentPage: 1, lastPage: 1, total: 0, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getPlans(page: 1, query: null)).thenAnswer((_) async => expected);
await mockFeedService.getPlans(page: 1, query: null);
verify(mockFeedService.getPlans(page: 1, query: null)).called(1);
});
test('getBlogPostComments returns comments', () async {
const id = "1";
final expected = CommentModel(
data: [
Comment(
id: 1,
authorName: 'user1',
authorSlug: '',
authorProfileIcon: '',
body: 'Nice',
childrenComments: [
Comment(id: 2, authorName: 'user2', authorSlug: '', authorProfileIcon: '', body: 'Great', childrenComments: [], createdAt: DateTime.now()),
],
createdAt: DateTime.now(),
),
],
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getBlogPostComments(id: id)).thenAnswer((_) async => expected);
await mockFeedService.getBlogPostComments(id: id);
verify(mockFeedService.getBlogPostComments(id: id)).called(1);
});
test('sendBlogPostComment sends comment', () async {
when(mockFeedService.sendBlogPostComment(id: "1", body: "Great", parentCommentId: null)).thenAnswer((_) async => Future.value());
await mockFeedService.sendBlogPostComment(id: "1", body: "Great", parentCommentId: null);
verify(mockFeedService.sendBlogPostComment(id: "1", body: "Great", parentCommentId: null)).called(1);
});
test('getDietsComments returns comments', () async {
const id = "5";
final expected = CommentModel(
data: [Comment(id: 2, authorName: 'user2', authorSlug: '', authorProfileIcon: '', body: 'Cool diet!', childrenComments: [], createdAt: DateTime.now())],
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getDietsComments(id: id)).thenAnswer((_) async => expected);
await mockFeedService.getDietsComments(id: id);
verify(mockFeedService.getDietsComments(id: id)).called(1);
});
test('sendDietsComment sends comment', () async {
when(mockFeedService.sendDietsComment(id: "5", body: "Nice diet", parentCommentId: null)).thenAnswer((_) async => Future.value());
await mockFeedService.sendDietsComment(id: "5", body: "Nice diet", parentCommentId: null);
verify(mockFeedService.sendDietsComment(id: "5", body: "Nice diet", parentCommentId: null)).called(1);
});
test('getPlansComments returns comments', () async {
const slug = "plan-1";
final expected = CommentModel(
data: [
Comment(id: 3, authorName: 'user3', authorSlug: '', authorProfileIcon: '', body: 'Super plan!', childrenComments: [], createdAt: DateTime.now()),
],
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getPlansComments(slug: slug)).thenAnswer((_) async => expected);
await mockFeedService.getPlansComments(slug: slug);
verify(mockFeedService.getPlansComments(slug: slug)).called(1);
});
test('sendPlansComment sends comment', () async {
when(mockFeedService.sendPlansComment(slug: "plan-1", body: "Ok", parentCommentId: null)).thenAnswer((_) async => Future.value());
await mockFeedService.sendPlansComment(slug: "plan-1", body: "Ok", parentCommentId: null);
verify(mockFeedService.sendPlansComment(slug: "plan-1", body: "Ok", parentCommentId: null)).called(1);
});
test('getRecipesComments returns comments', () async {
const id = "33";
final expected = CommentModel(
data: [
Comment(id: 4, authorName: 'user4', authorSlug: '', authorProfileIcon: '', body: 'Looks tasty!', childrenComments: [], createdAt: DateTime.now()),
],
links: const Links(first: '', last: '', prev: null, next: null),
meta: const Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getRecipesComments(id: id)).thenAnswer((_) async => expected);
await mockFeedService.getRecipesComments(id: id);
verify(mockFeedService.getRecipesComments(id: id)).called(1);
});
test('sendRecipesComment sends comment', () async {
when(mockFeedService.sendRecipesComment(id: "33", body: "Tasty", parentCommentId: null)).thenAnswer((_) async => Future.value());
await mockFeedService.sendRecipesComment(id: "33", body: "Tasty", parentCommentId: null);
verify(mockFeedService.sendRecipesComment(id: "33", body: "Tasty", parentCommentId: null)).called(1);
});
test('likeBlogPost works', () async {
when(mockFeedService.likeBlogPost(id: 1)).thenAnswer((_) async => Future.value());
await mockFeedService.likeBlogPost(id: 1);
verify(mockFeedService.likeBlogPost(id: 1)).called(1);
});
test('unlikedBlogPost works', () async {
when(mockFeedService.unlikedBlogPost(id: 1)).thenAnswer((_) async => Future.value());
await mockFeedService.unlikedBlogPost(id: 1);
verify(mockFeedService.unlikedBlogPost(id: 1)).called(1);
});
test('getConsultants returns consultant pagination', () async {
const expected = FeedConsultantPaginationModel(
data: [
FeedConsultantModel(
slug: 'consultant-1',
name: 'Anna Ivanova',
description: 'Test consultant description',
totalScores: 5,
photo: 'https://someurl.com/consultant1.jpg',
badges: [],
),
],
links: Links(first: '', last: '', prev: null, next: null),
meta: Meta(currentPage: 1, lastPage: 1, total: 1, perPage: 10, from: null, links: [Link(url: null, label: null, active: null)], to: null),
);
when(mockFeedService.getConsultants(name: 'Anna')).thenAnswer((_) async => expected);
await mockFeedService.getConsultants(name: 'Anna');
verify(mockFeedService.getConsultants(name: 'Anna')).called(1);
});
test('viewPost works', () async {
when(mockFeedService.viewPost(id: 1)).thenAnswer((_) async => Future.value());
await mockFeedService.viewPost(id: 1);
verify(mockFeedService.viewPost(id: 1)).called(1);
});
test('viewRecipe works', () async {
when(mockFeedService.viewRecipe(slug: 'abc')).thenAnswer((_) async => Future.value());
await mockFeedService.viewRecipe(slug: 'abc');
verify(mockFeedService.viewRecipe(slug: 'abc')).called(1);
});
test('viewDiet works', () async {
when(mockFeedService.viewDiet(id: 2)).thenAnswer((_) async => Future.value());
await mockFeedService.viewDiet(id: 2);
verify(mockFeedService.viewDiet(id: 2)).called(1);
});
test('viewPlan works', () async {
when(mockFeedService.viewPlan(slug: 'plan-7')).thenAnswer((_) async => Future.value());
await mockFeedService.viewPlan(slug: 'plan-7');
verify(mockFeedService.viewPlan(slug: 'plan-7')).called(1);
});
test('viewContent sends view model', () async {
final view = ViewModel(type: 'recipe', slugs: ['recipe-1']);
when(mockFeedService.viewContent(viewModel: view)).thenAnswer((_) async => Future.value());
await mockFeedService.viewContent(viewModel: view);
verify(mockFeedService.viewContent(viewModel: view)).called(1);
});
});
}