fix: plans - like and bookmark in consultant profile (#582)

- decouple PlanWidget from feed PlansCubit via owner-provided callbacks
- add like/favorite actions to profile PlansCubit: slug lookup, optimistic
  update, rollback of the affected plan, per-slug debounce, isClosed guards
- pass slug through like/favorite/comments events; guard out-of-range index
  in feed plans handlers and deep-link about_plan sync
- capture post like intent before await in profile blog post widget
- replace null force-unwraps in profile screen, guard indexOf == -1
- tests: profile plan like/bookmark, slug sync, bounds guards, #700 regression
This commit is contained in:
2026-11-20 16:30:13 +03:00
parent 1e8c1ab2eb
commit 0df474b2b5
22 changed files with 2139 additions and 137 deletions

View File

@@ -0,0 +1,194 @@
import 'package:easy_debounce/easy_debounce.dart';
import 'package:eatvio_app/core/models/pagination_model.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/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart';
import 'package:eatvio_app/features/feed/repositories/feed_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:rxdart/rxdart.dart';
import 'plans_cubit_slug_sync_test.mocks.dart';
@GenerateNiceMocks([MockSpec<FeedRepository>(), MockSpec<PlanRepository>()])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('feed PlansCubit — slug-based stream sync', () {
PlanModel plan({required String slug, int totalLikes = 10}) {
return PlanModel(
id: slug.hashCode,
slug: slug,
name: slug,
image: 'https://example.com/image.jpg',
duration: 7,
state: 'active',
type: const PlanType(
fit: true,
slim: false,
behavior: false,
wellness: false,
),
details: 'details',
packetsCount: 1,
minPriceOfOptions: 1000.0,
maxPriceOfOptions: 2000.0,
author: const Author(
authorSlug: 'author',
authorName: 'Author Name',
authorProfileIcon: 'https://example.com/icon.jpg',
authorIsMe: false,
isEntitySubscribedByMe: null,
authorPlaceInRating: null,
),
totalLikes: totalLikes,
totalViews: 100,
totalComments: 5,
wasLikedByMe: false,
isFavorite: false,
);
}
PlanPaginationModel pagination(List<PlanModel> plans) {
return PlanPaginationModel(
data: plans,
links: const Links(
first: 'https://example.com?page=1',
last: 'https://example.com?page=1',
prev: null,
next: null,
),
meta: Meta(
currentPage: 1,
from: 1,
lastPage: 1,
links: const [],
perPage: 10,
to: plans.length,
total: plans.length,
totalMinPrice: 1000,
totalMaxPrice: 2000,
),
);
}
late MockFeedRepository feedRepository;
late MockPlanRepository planRepository;
late BehaviorSubject<LikesState> likeState;
late BehaviorSubject<FavoriteState> favoriteState;
late BehaviorSubject<CommentsState> commentsState;
late PlansCubit cubit;
setUp(() async {
feedRepository = MockFeedRepository();
planRepository = MockPlanRepository();
likeState = BehaviorSubject<LikesState>();
favoriteState = BehaviorSubject<FavoriteState>();
commentsState = BehaviorSubject<CommentsState>();
when(planRepository.planLikeState).thenAnswer((_) => likeState);
when(planRepository.planFavoriteState).thenAnswer((_) => favoriteState);
when(planRepository.planCommentsState).thenAnswer((_) => commentsState);
when(
feedRepository.getPlans(
query: anyNamed('query'),
types: anyNamed('types'),
duration: anyNamed('duration'),
minPrice: anyNamed('minPrice'),
maxPrice: anyNamed('maxPrice'),
),
).thenAnswer(
(_) async => pagination([
plan(slug: 'plan-a'),
plan(slug: 'plan-b'),
]),
);
cubit = PlansCubit(
feedRepository: feedRepository,
planRepository: planRepository,
);
await cubit.loadPlans();
expect(cubit.state.plans.length, 2);
});
tearDown(() async {
EasyDebounce.cancel('loadPlans');
EasyDebounce.cancel('like_plan');
EasyDebounce.cancel('add_or_remove_plan_from_favorite');
if (!cubit.isClosed) {
await cubit.close();
}
await likeState.close();
await favoriteState.close();
await commentsState.close();
});
test('a like event with a slug updates the matching plan, not the index', () async {
likeState.add(
const LikesState(
slug: 'plan-b',
index: 0,
totalLikes: 42,
wasLikedByMe: true,
),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(cubit.state.plans[0].wasLikedByMe, isFalse);
expect(cubit.state.plans[0].totalLikes, 10);
expect(cubit.state.plans[1].wasLikedByMe, isTrue);
expect(cubit.state.plans[1].totalLikes, 42);
});
test('a like event with an unknown slug is a no-op', () async {
final before = cubit.state.plans;
likeState.add(
const LikesState(
slug: 'unknown-plan',
index: 0,
totalLikes: 42,
wasLikedByMe: true,
),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(cubit.state.plans, before);
});
test('a legacy like event without a slug keeps index behaviour', () async {
likeState.add(
const LikesState(index: 1, totalLikes: 42, wasLikedByMe: true),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(cubit.state.plans[1].wasLikedByMe, isTrue);
expect(cubit.state.plans[1].totalLikes, 42);
});
test('a favorite event with a slug updates the matching plan', () async {
favoriteState.add(
const FavoriteState(slug: 'plan-b', index: 0, isFavorite: true),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(cubit.state.plans[0].isFavorite, isFalse);
expect(cubit.state.plans[1].isFavorite, isTrue);
});
test('a comments event with a slug updates the matching plan', () async {
commentsState.add(
const CommentsState(slug: 'plan-b', index: 0, totalComments: 7),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(cubit.state.plans[0].totalComments, isNot(7));
expect(cubit.state.plans[1].totalComments, 7);
});
});
}

View File

@@ -0,0 +1,172 @@
import 'dart:async';
import 'package:easy_debounce/easy_debounce.dart';
import 'package:eatvio_app/core/models/pagination_model.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/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart';
import 'package:eatvio_app/features/feed/repositories/feed_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:rxdart/rxdart.dart';
import 'plans_cubit_sync_guard_test.mocks.dart';
@GenerateNiceMocks([MockSpec<FeedRepository>(), MockSpec<PlanRepository>()])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('feed PlansCubit — index bounds guard', () {
const testPlan = PlanModel(
id: 1,
slug: 'test-plan',
name: 'Test Plan',
image: 'https://example.com/image.jpg',
duration: 7,
state: 'active',
type: PlanType(fit: true, slim: false, behavior: false, wellness: false),
details: 'Test details',
packetsCount: 3,
minPriceOfOptions: 1000.0,
maxPriceOfOptions: 2000.0,
author: Author(
authorSlug: 'author',
authorName: 'Author Name',
authorProfileIcon: 'https://example.com/icon.jpg',
authorIsMe: false,
isEntitySubscribedByMe: null,
authorPlaceInRating: null,
),
totalLikes: 10,
totalViews: 100,
totalComments: 5,
wasLikedByMe: false,
isFavorite: false,
);
const plansPagination = PlanPaginationModel(
data: [testPlan],
links: Links(
first: 'https://example.com?page=1',
last: 'https://example.com?page=1',
prev: null,
next: null,
),
meta: Meta(
currentPage: 1,
from: 1,
lastPage: 1,
links: [],
perPage: 10,
to: 1,
total: 1,
totalMinPrice: 1000,
totalMaxPrice: 2000,
),
);
late MockFeedRepository feedRepository;
late MockPlanRepository planRepository;
late BehaviorSubject<LikesState> likeState;
late BehaviorSubject<FavoriteState> favoriteState;
late BehaviorSubject<CommentsState> commentsState;
setUp(() {
feedRepository = MockFeedRepository();
planRepository = MockPlanRepository();
likeState = BehaviorSubject<LikesState>();
favoriteState = BehaviorSubject<FavoriteState>();
commentsState = BehaviorSubject<CommentsState>();
when(planRepository.planLikeState).thenAnswer((_) => likeState);
when(planRepository.planFavoriteState).thenAnswer((_) => favoriteState);
when(planRepository.planCommentsState).thenAnswer((_) => commentsState);
when(
feedRepository.getPlans(
query: anyNamed('query'),
types: anyNamed('types'),
duration: anyNamed('duration'),
minPrice: anyNamed('minPrice'),
maxPrice: anyNamed('maxPrice'),
),
).thenAnswer((_) async => plansPagination);
});
tearDown(() async {
EasyDebounce.cancel('loadPlans');
EasyDebounce.cancel('like_plan');
EasyDebounce.cancel('add_or_remove_plan_from_favorite');
await likeState.close();
await favoriteState.close();
await commentsState.close();
});
/// Runs [body] in its own error zone so an unhandled stream-listener error
/// is captured instead of failing the test at teardown.
Future<List<Object>> errorsFrom(Future<void> Function() body) async {
final errors = <Object>[];
final done = Completer<void>();
runZonedGuarded(
() async {
try {
await body();
} finally {
done.complete();
}
},
(error, stackTrace) => errors.add(error),
);
await done.future;
return errors;
}
Future<PlansCubit> loadedCubit() async {
final cubit = PlansCubit(
feedRepository: feedRepository,
planRepository: planRepository,
);
await cubit.loadPlans();
expect(cubit.state.plans.length, 1);
return cubit;
}
test('an out-of-range like event is ignored instead of throwing', () async {
final errors = await errorsFrom(() async {
final cubit = await loadedCubit();
likeState.add(
const LikesState(index: 5, totalLikes: 99, wasLikedByMe: true),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
await cubit.close();
});
expect(errors, isEmpty);
});
test('an out-of-range favorite event is ignored instead of throwing', () async {
final errors = await errorsFrom(() async {
final cubit = await loadedCubit();
favoriteState.add(const FavoriteState(index: 5, isFavorite: true));
await Future<void>.delayed(const Duration(milliseconds: 100));
await cubit.close();
});
expect(errors, isEmpty);
});
test('an out-of-range comments event is ignored instead of throwing', () async {
final errors = await errorsFrom(() async {
final cubit = await loadedCubit();
commentsState.add(const CommentsState(index: 5, totalComments: 99));
await Future<void>.delayed(const Duration(milliseconds: 100));
await cubit.close();
});
expect(errors, isEmpty);
});
});
}

View File

@@ -1,5 +1,10 @@
import 'dart:async';
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
import 'package:eatvio_app/core/locator_service.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/repositories/plan_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plans_repository.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart';
@@ -9,14 +14,34 @@ import 'package:mockito/mockito.dart';
import 'plans_cubit_test.mocks.dart';
@GenerateNiceMocks([MockSpec<PlansRepository>()])
class _RecordingErrorReporter implements ErrorReporter {
final List<Object> errors = [];
@override
Future<void> report(
Object error,
StackTrace? stackTrace, {
String? origin,
Map<String, Object?>? extras,
}) async {
errors.add(error);
}
}
@GenerateNiceMocks([MockSpec<PlansRepository>(), MockSpec<PlanRepository>()])
void main() {
group('PlansCubit', () {
PlansCubit? cubit;
late MockPlansRepository mockRepository;
late MockPlanRepository mockPlanRepository;
setUp(() {
setUp(() async {
await sl.reset();
mockRepository = MockPlansRepository();
mockPlanRepository = MockPlanRepository();
when(mockPlanRepository.planLikeState).thenAnswer((_) => const Stream.empty());
when(mockPlanRepository.planFavoriteState).thenAnswer((_) => const Stream.empty());
when(mockPlanRepository.planCommentsState).thenAnswer((_) => const Stream.empty());
});
tearDown(() async {
@@ -24,16 +49,23 @@ void main() {
await cubit!.close();
cubit = null;
}
await sl.reset();
});
test('начальное состояние - пустое', () {
cubit = PlansCubit(plansRepository: mockRepository);
cubit = PlansCubit(
plansRepository: mockRepository,
planRepository: mockPlanRepository,
);
expect(cubit!.state, isA<PlansState>());
});
test('getPlans - успешная загрузка планов', () async {
cubit = PlansCubit(plansRepository: mockRepository);
cubit = PlansCubit(
plansRepository: mockRepository,
planRepository: mockPlanRepository,
);
final testPlans = [
const PlanModel(
@@ -75,7 +107,10 @@ void main() {
});
test('getPlans - обработка ошибки', () async {
cubit = PlansCubit(plansRepository: mockRepository);
cubit = PlansCubit(
plansRepository: mockRepository,
planRepository: mockPlanRepository,
);
when(mockRepository.getPlansBySlug(any))
.thenThrow(Exception('Ошибка загрузки'));
@@ -84,6 +119,33 @@ void main() {
expect(cubit!.state, isA<PlansStateError>());
});
test('getPlans - close during request does not emit loaded or report an error', () async {
final reporter = _RecordingErrorReporter();
sl.registerSingleton<ErrorReporter>(reporter);
cubit = PlansCubit(
plansRepository: mockRepository,
planRepository: mockPlanRepository,
);
final response = Completer<List<PlanModel>>();
when(mockRepository.getPlansBySlug('test-user'))
.thenAnswer((_) => response.future);
final emitted = <PlansState>[];
final subscription = cubit!.stream.listen(emitted.add);
final request = cubit!.getPlans('test-user');
await cubit!.close();
response.complete(const <PlanModel>[]);
await request;
await subscription.cancel();
expect(emitted.whereType<PlansStateLoaded>(), isEmpty);
expect(emitted.whereType<PlansStateError>(), isEmpty);
expect(reporter.errors, isEmpty);
});
});
}

View File

@@ -0,0 +1,363 @@
import 'dart:async';
import 'package:easy_debounce/easy_debounce.dart';
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/features/diets/repositories/diet_repository.dart';
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plans_repository.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:rxdart/rxdart.dart';
import '../../../../../fixtures/fixture_reader.dart';
import 'profile_plans_cubit_like_test.mocks.dart';
@GenerateNiceMocks([MockSpec<PlansRepository>(), MockSpec<PlanRepository>()])
class _RecordingReporter implements ErrorReporter {
final List<Object> errors = [];
Object? lastError;
StackTrace? lastStack;
String? lastOrigin;
@override
Future<void> report(
Object error,
StackTrace? stackTrace, {
String? origin,
Map<String, Object?>? extras,
}) async {
errors.add(error);
lastError = error;
lastStack = stackTrace;
lastOrigin = origin;
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('profile PlansCubit — like/favorite', () {
late MockPlansRepository plansRepository;
late MockPlanRepository planRepository;
late PlansCubit cubit;
late _RecordingReporter reporter;
late List<MethodCall> toastCalls;
const slugA = 'plan-a';
const slugB = 'plan-b';
PlanModel plan({
String slug = slugA,
bool wasLikedByMe = false,
bool isFavorite = false,
int totalLikes = 10,
}) {
return PlanModel.fromJson(
FixtureReader.readAsMap('plans/plan_response.json'),
).copyWith(
slug: slug,
state: 'active',
wasLikedByMe: wasLikedByMe,
isFavorite: isFavorite,
totalLikes: totalLikes,
);
}
setUpAll(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('PonnamKarthik/fluttertoast'),
(MethodCall methodCall) async {
toastCalls.add(methodCall);
return null;
},
);
});
setUp(() async {
await sl.reset();
reporter = _RecordingReporter();
sl.registerSingleton<ErrorReporter>(reporter);
toastCalls = <MethodCall>[];
plansRepository = MockPlansRepository();
planRepository = MockPlanRepository();
when(
planRepository.planLikeState,
).thenAnswer((_) => BehaviorSubject<LikesState>());
when(
planRepository.planFavoriteState,
).thenAnswer((_) => BehaviorSubject<FavoriteState>());
when(
planRepository.planCommentsState,
).thenAnswer((_) => BehaviorSubject<CommentsState>());
cubit = PlansCubit(
plansRepository: plansRepository,
planRepository: planRepository,
);
});
tearDown(() async {
EasyDebounce.cancel('profile_like_plan_$slugA');
EasyDebounce.cancel('profile_like_plan_$slugB');
EasyDebounce.cancel('profile_favorite_$slugA');
EasyDebounce.cancel('profile_favorite_$slugB');
if (!cubit.isClosed) {
await cubit.close();
}
await sl.reset();
});
Future<void> load(List<PlanModel> plans) async {
when(plansRepository.getPlansBySlug(any)).thenAnswer((_) async => plans);
await cubit.getPlans('consultant');
expect(cubit.state, isA<PlansStateLoaded>());
}
PlansStateLoaded loaded() => cubit.state as PlansStateLoaded;
test(
'likePlan adds a like optimistically and calls the repository once',
() async {
await load([plan()]);
await cubit.likePlan(slugA);
expect(loaded().plansList.single.wasLikedByMe, isTrue);
expect(loaded().plansList.single.totalLikes, 11);
await Future<void>.delayed(const Duration(milliseconds: 1200));
verify(planRepository.likePlan(slugA)).called(1);
},
);
test('likePlan removes an existing like optimistically', () async {
await load([plan(wasLikedByMe: true, totalLikes: 10)]);
await cubit.likePlan(slugA);
expect(loaded().plansList.single.wasLikedByMe, isFalse);
expect(loaded().plansList.single.totalLikes, 9);
await Future<void>.delayed(const Duration(milliseconds: 1200));
verify(planRepository.likePlan(slugA)).called(1);
});
test(
'likePlan rolls back the optimistic change when the repository fails',
() async {
when(planRepository.likePlan(any)).thenThrow(Exception('network'));
await load([plan()]);
await cubit.likePlan(slugA);
expect(loaded().plansList.single.wasLikedByMe, isTrue);
await Future<void>.delayed(const Duration(milliseconds: 1200));
expect(loaded().plansList.single.wasLikedByMe, isFalse);
expect(loaded().plansList.single.totalLikes, 10);
verify(planRepository.likePlan(slugA)).called(1);
},
);
test(
'likePlan does nothing when the slug is not in the loaded list',
() async {
await load([plan()]);
final before = loaded().plansList;
await cubit.likePlan('missing-plan');
await Future<void>.delayed(const Duration(milliseconds: 1200));
expect(loaded().plansList, before);
verifyNever(planRepository.likePlan(any));
},
);
test('likePlan does nothing when state is not loaded', () async {
await cubit.likePlan(slugA);
await Future<void>.delayed(const Duration(milliseconds: 1200));
expect(cubit.state, isNot(isA<PlansStateLoaded>()));
verifyNever(planRepository.likePlan(any));
});
test(
'likePlan debounces repeated taps on the same slug into one request',
() async {
await load([plan()]);
await cubit.likePlan(slugA);
await cubit.likePlan(slugA);
await Future<void>.delayed(const Duration(milliseconds: 1200));
verify(planRepository.likePlan(slugA)).called(1);
},
);
test('likePlan keeps a separate debounce per slug', () async {
await load([plan(slug: slugA), plan(slug: slugB)]);
await cubit.likePlan(slugA);
await cubit.likePlan(slugB);
await Future<void>.delayed(const Duration(milliseconds: 1200));
verify(planRepository.likePlan(slugA)).called(1);
verify(planRepository.likePlan(slugB)).called(1);
});
test(
'addPlanToFavorite sets favorite optimistically and calls the repository',
() async {
await load([plan()]);
await cubit.addPlanToFavorite(slugA);
expect(loaded().plansList.single.isFavorite, isTrue);
await Future<void>.delayed(const Duration(milliseconds: 1200));
verify(planRepository.addToFavorite(slugA)).called(1);
},
);
test('addPlanToFavorite rolls back when the repository fails', () async {
when(planRepository.addToFavorite(any)).thenThrow(Exception('network'));
await load([plan()]);
await cubit.addPlanToFavorite(slugA);
expect(loaded().plansList.single.isFavorite, isTrue);
await Future<void>.delayed(const Duration(milliseconds: 1200));
expect(loaded().plansList.single.isFavorite, isFalse);
verify(planRepository.addToFavorite(slugA)).called(1);
});
test(
'removePlanFromFavorite clears favorite optimistically and calls the repository',
() async {
await load([plan(isFavorite: true)]);
await cubit.removePlanFromFavorite(slugA);
expect(loaded().plansList.single.isFavorite, isFalse);
await Future<void>.delayed(const Duration(milliseconds: 1200));
verify(planRepository.removeFromFavorite(slugA)).called(1);
},
);
test(
'favorite actions do nothing when the slug is not in the loaded list',
() async {
await load([plan()]);
final before = loaded().plansList;
await cubit.addPlanToFavorite('missing-plan');
await cubit.removePlanFromFavorite('missing-plan');
await Future<void>.delayed(const Duration(milliseconds: 1200));
expect(loaded().plansList, before);
verifyNever(planRepository.addToFavorite(any));
verifyNever(planRepository.removeFromFavorite(any));
},
);
test('close cancels a pending like request', () async {
await load([plan()]);
await cubit.likePlan(slugA);
await cubit.close();
await Future<void>.delayed(const Duration(milliseconds: 1200));
verifyNever(planRepository.likePlan(any));
});
test('a debounced failure after close does not emit or throw', () async {
when(planRepository.likePlan(any)).thenAnswer((_) async {
await Future<void>.delayed(const Duration(milliseconds: 50));
throw Exception('network');
});
await load([plan()]);
await cubit.likePlan(slugA);
await Future<void>.delayed(const Duration(milliseconds: 300));
await cubit.close();
await Future<void>.delayed(const Duration(milliseconds: 300));
expect(cubit.isClosed, isTrue);
});
test(
'a like that fails after close neither emits after close nor leaks a zone error',
() async {
await load([plan()]);
final zoneErrors = <Object>[];
await runZonedGuarded(() async {
final pending = Completer<void>();
when(planRepository.likePlan(any)).thenAnswer((_) => pending.future);
await cubit.likePlan(slugA);
await Future<void>.delayed(const Duration(milliseconds: 250));
verify(planRepository.likePlan(slugA)).called(1);
await cubit.close();
pending.completeError(Exception('network'));
await Future<void>.delayed(const Duration(milliseconds: 100));
}, (error, stackTrace) {
zoneErrors.add(error);
});
expect(cubit.isClosed, isTrue);
expect(
zoneErrors.whereType<StateError>().where(
(error) => error.message.contains('Cannot emit new states after calling close'),
),
isEmpty,
);
expect(zoneErrors, isEmpty, reason: 'errors in zone: $zoneErrors');
},
);
test(
'addPlanToFavorite rolls back and shows an error toast when the repository fails',
() async {
when(planRepository.addToFavorite(any)).thenThrow(Exception('network'));
await load([plan()]);
await cubit.addPlanToFavorite(slugA);
await Future<void>.delayed(const Duration(milliseconds: 1200));
expect(loaded().plansList.single.isFavorite, isFalse);
final showToastCalls = toastCalls.where((call) => call.method == 'showToast').toList();
expect(showToastCalls, isNotEmpty);
final arguments = showToastCalls.single.arguments as Map;
expect(arguments['msg'], contains('Произошла ошибка'));
},
);
test('likePlan reports the failure through ErrorReporter', () async {
final error = Exception('network');
when(planRepository.likePlan(any)).thenThrow(error);
await load([plan()]);
await cubit.likePlan(slugA);
await Future<void>.delayed(const Duration(milliseconds: 1200));
expect(reporter.errors, isNotEmpty);
expect(reporter.lastError, same(error));
expect(reporter.lastOrigin, 'PlansCubit');
expect(reporter.lastOrigin, isNotEmpty);
});
});
}

View File

@@ -0,0 +1,127 @@
import 'package:easy_debounce/easy_debounce.dart';
import 'package:eatvio_app/features/diets/repositories/diet_repository.dart';
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plans_repository.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:rxdart/rxdart.dart';
import '../../../../../fixtures/fixture_reader.dart';
import 'profile_plans_cubit_slug_sync_test.mocks.dart';
@GenerateNiceMocks([MockSpec<PlansRepository>(), MockSpec<PlanRepository>()])
void main() {
group('profile PlansCubit — slug-based stream sync', () {
late MockPlansRepository plansRepository;
late MockPlanRepository planRepository;
late BehaviorSubject<LikesState> likeState;
late BehaviorSubject<FavoriteState> favoriteState;
late BehaviorSubject<CommentsState> commentsState;
late PlansCubit cubit;
PlanModel plan({required String slug, int totalLikes = 10}) {
return PlanModel.fromJson(
FixtureReader.readAsMap('plans/plan_response.json'),
).copyWith(
slug: slug,
state: 'active',
wasLikedByMe: false,
isFavorite: false,
totalLikes: totalLikes,
);
}
setUp(() async {
plansRepository = MockPlansRepository();
planRepository = MockPlanRepository();
likeState = BehaviorSubject<LikesState>();
favoriteState = BehaviorSubject<FavoriteState>();
commentsState = BehaviorSubject<CommentsState>();
when(planRepository.planLikeState).thenAnswer((_) => likeState);
when(planRepository.planFavoriteState).thenAnswer((_) => favoriteState);
when(planRepository.planCommentsState).thenAnswer((_) => commentsState);
cubit = PlansCubit(
plansRepository: plansRepository,
planRepository: planRepository,
);
when(
plansRepository.getPlansBySlug(any),
).thenAnswer((_) async => [plan(slug: 'plan-a'), plan(slug: 'plan-b')]);
await cubit.getPlans('consultant');
expect(cubit.state, isA<PlansStateLoaded>());
});
tearDown(() async {
EasyDebounce.cancel('profile_like_plan_plan-a');
EasyDebounce.cancel('profile_like_plan_plan-b');
if (!cubit.isClosed) {
await cubit.close();
}
await likeState.close();
await favoriteState.close();
await commentsState.close();
});
PlansStateLoaded loaded() => cubit.state as PlansStateLoaded;
test('a like event with a slug updates only the matching plan', () async {
likeState.add(
const LikesState(
slug: 'plan-b',
totalLikes: 42,
wasLikedByMe: true,
index: 0,
),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(loaded().plansList[0].wasLikedByMe, isFalse);
expect(loaded().plansList[0].totalLikes, 10);
expect(loaded().plansList[1].wasLikedByMe, isTrue);
expect(loaded().plansList[1].totalLikes, 42);
});
test('a like event with an unknown slug is a no-op', () async {
final before = loaded().plansList;
likeState.add(
const LikesState(
slug: 'unknown-plan',
totalLikes: 42,
wasLikedByMe: true,
index: 0,
),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(loaded().plansList, before);
});
test('a favorite event with a slug updates only the matching plan', () async {
favoriteState.add(
const FavoriteState(slug: 'plan-b', isFavorite: true, index: 0),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(loaded().plansList[0].isFavorite, isFalse);
expect(loaded().plansList[1].isFavorite, isTrue);
});
test('a comments event with a slug updates only the matching plan', () async {
commentsState.add(
const CommentsState(slug: 'plan-b', totalComments: 7, index: 0),
);
await Future<void>.delayed(const Duration(milliseconds: 100));
expect(loaded().plansList[0].totalComments, isNot(7));
expect(loaded().plansList[1].totalComments, 7);
});
});
}

View File

@@ -0,0 +1,133 @@
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart';
import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart';
import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import '../../../../../fixtures/feed_fixtures.dart';
import 'profile_cubit_update_feed_regression_test.mocks.dart';
@GenerateNiceMocks([
MockSpec<ProfileRepository>(),
MockSpec<ChatRepository>(),
MockSpec<ConsultantRepository>(),
])
void main() {
group('ProfileCubit.updateFeedBlogPostList — regression #700', () {
late ProfileCubit cubit;
const profile = ProfileModel(
id: 1,
name: 'Consultant',
email: 'c@e.com',
phoneConfirmationState: 'confirmed',
slug: 'consultant',
isPublicProfile: true,
isBlockedByMe: false,
isBlockedByAuthor: false,
isBlockedByUser: false,
isEntitySubscribedByMe: false,
profilePhotoUrl: '',
roles: ['consultant'],
badges: [],
subscriptions: [],
subscribers: [],
);
const details = ProfileDetailsModel(
firstName: 'Test',
lastName: 'User',
birthdate: '1990-01-01',
gender: 'male',
country: 'Russia',
city: 'Moscow',
lang: 'ru',
weight: 70.0,
height: 175,
chestCircumference: 100,
waistCircumference: 80,
hipCircumference: 90,
bloodPressureUp: 120,
bloodPressureDown: 80,
hasHypo: false,
hasHyper: false,
aboutAlergy: '',
aboutTakingPils: '',
aboutSportHobbies: '',
favoriteFoods: '',
unfavoriteFoods: '',
additionalInfo: '',
isMoodFillable: true,
isBedtimeFillable: true,
activityCoefficient: 1.5,
);
const consultantInfo = ConsultationRequestModel(
ratingPlace: 3,
educationModel: EducationModel(
hasMedicalEducation: 1,
completedCourses: null,
requestState: ModerationStatus.approved,
),
photos: [],
);
const certPhotos = [
ConsultantCertPhotoModel(
id: 7,
group: ConsultantCertPhotoModel.visibleGroup,
originalName: 'cert.jpg',
path: 'cert.jpg',
size: 100,
url: 'https://example.com/cert.jpg',
),
];
setUp(() {
cubit = ProfileCubit(
profileRepository: MockProfileRepository(),
chatRepository: MockChatRepository(),
consultantRepository: MockConsultantRepository(),
);
});
tearDown(() async {
if (!cubit.isClosed) {
await cubit.close();
}
});
test('preserves consultantInfo, certPhotos and isMyProfile on like emit', () {
final post = FeedFixtures.feedBlogPostModel().copyWith(
wasLikedByMe: false,
totalLikes: 10,
);
cubit.emit(
ProfileState.loaded(
profile: profile,
profileDetails: details,
blogPosts: [post],
isMyProfile: true,
certPhotos: certPhotos,
consultantInfo: consultantInfo,
),
);
cubit.updateFeedBlogPostList(post, true);
final state = cubit.state as ProfileStateLoaded;
expect(state.isMyProfile, isTrue);
expect(state.consultantInfo, consultantInfo);
expect(state.certPhotos, certPhotos);
expect(state.profile, profile);
expect(state.profileDetails, details);
expect(state.blogPosts.single.wasLikedByMe, isTrue);
expect(state.blogPosts.single.totalLikes, 11);
});
});
}

View File

@@ -0,0 +1,211 @@
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/theme/theme_helper.dart';
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart';
import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart';
import 'package:eatvio_app/features/insights/repositories/insights_repository.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart'
as profile_plans;
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/pages/profile_screen.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plans_repository.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:network_image_mock/network_image_mock.dart';
import '../../../../fixtures/doubles/insights_doubles.dart';
import 'profile_screen_consultant_null_links_test.mocks.dart';
@GenerateNiceMocks([
MockSpec<ProfileRepository>(),
MockSpec<ChatRepository>(),
MockSpec<ConsultantRepository>(),
MockSpec<PlansRepository>(),
MockSpec<PlanRepository>(),
])
void main() {
group('ProfileScreen — consultant without social links', () {
late MockProfileRepository profileRepository;
late MockChatRepository chatRepository;
late MockConsultantRepository consultantRepository;
late MockPlansRepository plansRepository;
late MockPlanRepository planRepository;
setUpAll(() async {
dotenv.loadFromString(
envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost',
);
});
setUp(() async {
await sl.reset();
sl.registerLazySingleton<AppConfig>(
() =>
AppConfig(buildType: AppBuildType.tests)
..setBaseUrl('http://localhost'),
);
profileRepository = MockProfileRepository();
chatRepository = MockChatRepository();
consultantRepository = MockConsultantRepository();
plansRepository = MockPlansRepository();
planRepository = MockPlanRepository();
when(
planRepository.planLikeState,
).thenAnswer((_) => const Stream.empty());
when(
planRepository.planFavoriteState,
).thenAnswer((_) => const Stream.empty());
when(
planRepository.planCommentsState,
).thenAnswer((_) => const Stream.empty());
sl.registerLazySingleton<ProfileRepository>(() => profileRepository);
sl.registerLazySingleton<InsightsRepository>(
() => FakeInsightsRepository(),
);
sl.registerLazySingleton<ChatRepository>(() => chatRepository);
sl.registerLazySingleton<ConsultantRepository>(
() => consultantRepository,
);
sl.registerLazySingleton<PlansRepository>(() => plansRepository);
sl.registerLazySingleton<PlanRepository>(() => planRepository);
sl.registerFactory<ProfileCubit>(
() => ProfileCubit(
profileRepository: sl(),
chatRepository: sl(),
consultantRepository: sl(),
),
);
sl.registerFactory<profile_plans.PlansCubit>(
() => profile_plans.PlansCubit(
plansRepository: sl(),
planRepository: sl(),
),
);
});
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: Scaffold(body: child),
);
}
ProfileModel profileOf(String slug, {List<String> roles = const []}) {
return ProfileModel(
id: 1,
name: 'Test User',
email: 'test@example.com',
phoneConfirmationState: 'confirmed',
slug: slug,
isPublicProfile: true,
isBlockedByMe: false,
isBlockedByAuthor: false,
isBlockedByUser: false,
isEntitySubscribedByMe: false,
profilePhotoUrl: '',
roles: roles,
badges: const [],
subscriptions: const [],
subscribers: const [],
);
}
const details = ProfileDetailsModel(
firstName: 'Test',
lastName: 'User',
birthdate: '1990-01-01',
gender: 'male',
country: 'Russia',
city: 'Moscow',
lang: 'ru',
weight: 70.0,
height: 175,
chestCircumference: 100,
waistCircumference: 80,
hipCircumference: 90,
bloodPressureUp: 120,
bloodPressureDown: 80,
hasHypo: false,
hasHyper: false,
aboutAlergy: '',
aboutTakingPils: '',
aboutSportHobbies: '',
favoriteFoods: '',
unfavoriteFoods: '',
additionalInfo: '',
isMoodFillable: true,
isBedtimeFillable: true,
activityCoefficient: 1.5,
);
const consultantInfo = ConsultationRequestModel(
ratingPlace: 5,
educationModel: EducationModel(
hasMedicalEducation: 0,
completedCourses: null,
vkLink: null,
instaLink: null,
fbLink: null,
tgLink: null,
personalSiteLink: null,
requestState: ModerationStatus.approved,
),
photos: [],
);
testWidgets(
'a consultant with null social links renders without an ErrorWidget',
(tester) async {
when(profileRepository.getProfileBySlug(any)).thenAnswer(
(_) async => profileOf('other-consultant', roles: ['consultant']),
);
when(
profileRepository.getMyProfile(),
).thenAnswer((_) async => profileOf('me'));
when(
profileRepository.getProfileDetailsBySlug(any),
).thenAnswer((_) async => details);
when(
profileRepository.getBlogPostsByAuthorSlug(slug: anyNamed('slug')),
).thenAnswer((_) async => []);
when(
consultantRepository.getConsultantRequestStatus(any),
).thenAnswer((_) async => consultantInfo);
when(plansRepository.getPlansBySlug(any)).thenAnswer((_) async => []);
await mockNetworkImagesFor(() async {
await tester.pumpWidget(
wrap(const ProfileScreen(slug: 'other-consultant')),
);
await tester.pumpAndSettle();
});
expect(tester.takeException(), isNull);
expect(find.byType(ErrorWidget), findsNothing);
expect(find.byType(ProfileScreen), findsOneWidget);
},
);
});
}

View File

@@ -0,0 +1,272 @@
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/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/bookmark_button.dart';
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart';
import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart';
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/features/insights/repositories/insights_repository.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart'
as profile_plans;
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/pages/profile_screen.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plans_repository.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_portal/flutter_portal.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:network_image_mock/network_image_mock.dart';
import '../../../../fixtures/doubles/insights_doubles.dart';
import '../../../../fixtures/fixture_reader.dart';
import 'profile_screen_plan_like_test.mocks.dart';
@GenerateNiceMocks([
MockSpec<ProfileRepository>(),
MockSpec<ChatRepository>(),
MockSpec<ConsultantRepository>(),
MockSpec<PlansRepository>(),
MockSpec<PlanRepository>(),
])
void main() {
group('ProfileScreen — план консультанта', () {
late MockProfileRepository profileRepository;
late MockChatRepository chatRepository;
late MockConsultantRepository consultantRepository;
late MockPlansRepository plansRepository;
late MockPlanRepository planRepository;
setUpAll(() async {
dotenv.loadFromString(
envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost',
);
});
setUp(() async {
await sl.reset();
sl.registerLazySingleton<AppConfig>(
() =>
AppConfig(buildType: AppBuildType.tests)
..setBaseUrl('http://localhost'),
);
profileRepository = MockProfileRepository();
chatRepository = MockChatRepository();
consultantRepository = MockConsultantRepository();
plansRepository = MockPlansRepository();
planRepository = MockPlanRepository();
when(
planRepository.planLikeState,
).thenAnswer((_) => const Stream.empty());
when(
planRepository.planFavoriteState,
).thenAnswer((_) => const Stream.empty());
when(
planRepository.planCommentsState,
).thenAnswer((_) => const Stream.empty());
when(planRepository.likePlan(any)).thenAnswer((_) async {});
when(planRepository.addToFavorite(any)).thenAnswer((_) async {});
when(planRepository.removeFromFavorite(any)).thenAnswer((_) async {});
sl.registerLazySingleton<ProfileRepository>(() => profileRepository);
sl.registerLazySingleton<InsightsRepository>(
() => FakeInsightsRepository(),
);
sl.registerLazySingleton<ChatRepository>(() => chatRepository);
sl.registerLazySingleton<ConsultantRepository>(
() => consultantRepository,
);
sl.registerLazySingleton<PlansRepository>(() => plansRepository);
sl.registerLazySingleton<PlanRepository>(() => planRepository);
sl.registerFactory<ProfileCubit>(
() => ProfileCubit(
profileRepository: sl(),
chatRepository: sl(),
consultantRepository: sl(),
),
);
sl.registerFactory<profile_plans.PlansCubit>(
() => profile_plans.PlansCubit(
plansRepository: sl(),
planRepository: sl(),
),
);
});
tearDown(() async {
await sl.reset();
});
Widget wrap(Widget child) {
return Portal(
child: MaterialApp(
theme: ThemeHelper().themeData(),
localizationsDelegates: const [
S.delegate,
...GlobalMaterialLocalizations.delegates,
],
supportedLocales: const [Locale('ru')],
home: Scaffold(body: child),
),
);
}
ProfileModel profileOf(String slug, {List<String> roles = const []}) {
return ProfileModel(
id: 1,
name: 'Test User',
email: 'test@example.com',
phoneConfirmationState: 'confirmed',
slug: slug,
isPublicProfile: true,
isBlockedByMe: false,
isBlockedByAuthor: false,
isBlockedByUser: false,
isEntitySubscribedByMe: false,
profilePhotoUrl: '',
roles: roles,
badges: const [],
subscriptions: const [],
subscribers: const [],
);
}
const details = ProfileDetailsModel(
firstName: 'Test',
lastName: 'User',
birthdate: '1990-01-01',
gender: 'male',
country: 'Russia',
city: 'Moscow',
lang: 'ru',
weight: 70.0,
height: 175,
chestCircumference: 100,
waistCircumference: 80,
hipCircumference: 90,
bloodPressureUp: 120,
bloodPressureDown: 80,
hasHypo: false,
hasHyper: false,
aboutAlergy: '',
aboutTakingPils: '',
aboutSportHobbies: '',
favoriteFoods: '',
unfavoriteFoods: '',
additionalInfo: '',
isMoodFillable: true,
isBedtimeFillable: true,
activityCoefficient: 1.5,
);
const consultantInfo = ConsultationRequestModel(
ratingPlace: 5,
educationModel: EducationModel(
hasMedicalEducation: 0,
completedCourses: null,
vkLink: '',
instaLink: '',
fbLink: '',
tgLink: '',
personalSiteLink: '',
requestState: ModerationStatus.approved,
),
photos: [],
);
PlanModel activePlan() {
return PlanModel.fromJson(
FixtureReader.readAsMap('plans/plan_response.json'),
).copyWith(
state: 'active',
wasLikedByMe: false,
isFavorite: false,
totalLikes: 10,
);
}
Future<void> pumpConsultantProfile(WidgetTester tester) async {
when(profileRepository.getProfileBySlug(any)).thenAnswer(
(_) async => profileOf('other-consultant', roles: ['consultant']),
);
when(
profileRepository.getMyProfile(),
).thenAnswer((_) async => profileOf('me'));
when(
profileRepository.getProfileDetailsBySlug(any),
).thenAnswer((_) async => details);
when(
profileRepository.getBlogPostsByAuthorSlug(slug: anyNamed('slug')),
).thenAnswer((_) async => []);
when(
consultantRepository.getConsultantRequestStatus(any),
).thenAnswer((_) async => consultantInfo);
when(
plansRepository.getPlansBySlug(any),
).thenAnswer((_) async => [activePlan()]);
await mockNetworkImagesFor(() async {
await tester.pumpWidget(
wrap(const ProfileScreen(slug: 'other-consultant')),
);
await tester.pumpAndSettle();
// ExpandablePageView measures its height in a post-frame callback,
// so the plan card appears only after an extra frame.
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
});
}
testWidgets(
'tapping like on a consultant plan in someone else profile updates like state',
(tester) async {
await pumpConsultantProfile(tester);
final likeButton = find.byIcon(Icons.favorite_border_rounded);
expect(likeButton, findsOneWidget);
await tester.ensureVisible(likeButton);
await tester.pump();
await tester.tap(likeButton);
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(tester.takeException(), isNull);
expect(find.byIcon(Icons.favorite_rounded), findsOneWidget);
expect(find.text('11'), findsOneWidget);
},
);
testWidgets(
'tapping bookmark on a consultant plan in someone else profile updates favorite state',
(tester) async {
await pumpConsultantProfile(tester);
final bookmark = find.descendant(
of: find.byType(BookmarkButton),
matching: find.byIcon(Icons.bookmark_border_rounded),
);
expect(bookmark, findsOneWidget);
await tester.ensureVisible(bookmark);
await tester.pump();
await tester.tap(bookmark);
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(tester.takeException(), isNull);
expect(find.byIcon(Icons.bookmark), findsOneWidget);
},
);
});
}

View File

@@ -12,6 +12,7 @@ import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/pages/profile_screen.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
import 'package:eatvio_app/features/plans/repositories/plans_repository.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:material_ui/material_ui.dart';
@@ -29,6 +30,7 @@ import 'profile_screen_smoke_test.mocks.dart';
MockSpec<ChatRepository>(),
MockSpec<ConsultantRepository>(),
MockSpec<PlansRepository>(),
MockSpec<PlanRepository>(),
])
void main() {
group('ProfileScreen smoke', () {
@@ -36,6 +38,7 @@ void main() {
late MockChatRepository chatRepository;
late MockConsultantRepository consultantRepository;
late MockPlansRepository plansRepository;
late MockPlanRepository planRepository;
setUpAll(() async {
dotenv.loadFromString(
@@ -55,6 +58,11 @@ void main() {
chatRepository = MockChatRepository();
consultantRepository = MockConsultantRepository();
plansRepository = MockPlansRepository();
planRepository = MockPlanRepository();
when(planRepository.planLikeState).thenAnswer((_) => const Stream.empty());
when(planRepository.planFavoriteState).thenAnswer((_) => const Stream.empty());
when(planRepository.planCommentsState).thenAnswer((_) => const Stream.empty());
sl.registerLazySingleton<ProfileRepository>(() => profileRepository);
sl.registerLazySingleton<InsightsRepository>(
@@ -65,6 +73,7 @@ void main() {
() => consultantRepository,
);
sl.registerLazySingleton<PlansRepository>(() => plansRepository);
sl.registerLazySingleton<PlanRepository>(() => planRepository);
sl.registerFactory<ProfileCubit>(
() => ProfileCubit(
@@ -74,7 +83,10 @@ void main() {
),
);
sl.registerFactory<profile_plans.PlansCubit>(
() => profile_plans.PlansCubit(plansRepository: sl()),
() => profile_plans.PlansCubit(
plansRepository: sl(),
planRepository: sl(),
),
);
});

View File

@@ -0,0 +1,256 @@
import 'dart:async';
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/theme/theme_helper.dart';
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/profile_blog_post_widget.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.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';
import 'package:flutter_portal/flutter_portal.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:network_image_mock/network_image_mock.dart';
import '../../../../fixtures/feed_fixtures.dart';
import 'profile_blog_post_widget_like_test.mocks.dart';
@GenerateNiceMocks([
MockSpec<ProfileCubit>(),
MockSpec<FeedCubit>(),
MockSpec<ProfileRepository>(),
MockSpec<ChatRepository>(),
MockSpec<ConsultantRepository>(),
])
void main() {
group('ProfileBlogPostWidget — like', () {
setUpAll(() async {
dotenv.loadFromString(
envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost',
);
});
setUp(() async {
await sl.reset();
sl.registerLazySingleton<AppConfig>(
() =>
AppConfig(buildType: AppBuildType.tests)
..setBaseUrl('http://localhost'),
);
});
tearDown(() async {
await sl.reset();
});
const profile = ProfileModel(
id: 1,
name: 'User',
email: 'u@e.com',
phoneConfirmationState: 'confirmed',
slug: 'user',
isPublicProfile: true,
isBlockedByMe: false,
isBlockedByAuthor: false,
isBlockedByUser: false,
isEntitySubscribedByMe: false,
profilePhotoUrl: '',
roles: [],
badges: [],
subscriptions: [],
subscribers: [],
);
const details = ProfileDetailsModel(
firstName: 'Test',
lastName: 'User',
birthdate: '1990-01-01',
gender: 'male',
country: 'Russia',
city: 'Moscow',
lang: 'ru',
weight: 70.0,
height: 175,
chestCircumference: 100,
waistCircumference: 80,
hipCircumference: 90,
bloodPressureUp: 120,
bloodPressureDown: 80,
hasHypo: false,
hasHyper: false,
aboutAlergy: '',
aboutTakingPils: '',
aboutSportHobbies: '',
favoriteFoods: '',
unfavoriteFoods: '',
additionalInfo: '',
isMoodFillable: true,
isBedtimeFillable: true,
activityCoefficient: 1.5,
);
ProfileState loadedState() {
return ProfileState.loaded(
profile: profile,
profileDetails: details,
blogPosts: [
FeedFixtures.feedBlogPostModel().copyWith(
wasLikedByMe: false,
totalLikes: 10,
),
],
isMyProfile: true,
certPhotos: const [],
);
}
Widget wrap({
required ProfileCubit profileCubit,
required FeedCubit feedCubit,
}) {
return Portal(
child: MaterialApp(
theme: ThemeHelper().themeData(),
localizationsDelegates: const [
S.delegate,
...GlobalMaterialLocalizations.delegates,
],
supportedLocales: const [Locale('ru')],
home: Scaffold(
body: MediaQuery(
data: const MediaQueryData(size: Size(800, 1600)),
child: SingleChildScrollView(
child: BlocProvider<FeedCubit>.value(
value: feedCubit,
child: ProfileBlogPostWidget(
index: 0,
profileCubit: profileCubit,
),
),
),
),
),
),
);
}
testWidgets(
'passes the new like value to updateFeedBlogPostList before the request completes',
(tester) async {
final profileCubit = _RecordingProfileCubit(
profileRepository: MockProfileRepository(),
chatRepository: MockChatRepository(),
consultantRepository: MockConsultantRepository(),
);
addTearDown(profileCubit.close);
profileCubit.emit(loadedState());
final expectedPost =
(profileCubit.state as ProfileStateLoaded).blogPosts.single;
final feedCubit = MockFeedCubit();
final likeCompleter = Completer<void>();
when(feedCubit.likePost(any)).thenAnswer((_) => likeCompleter.future);
await mockNetworkImagesFor(() async {
await tester.pumpWidget(
wrap(profileCubit: profileCubit, feedCubit: feedCubit),
);
await tester.pumpAndSettle();
final likeButton = find.byIcon(Icons.favorite_border_rounded);
await tester.ensureVisible(likeButton);
await tester.pump();
await tester.tap(likeButton);
// A frame while the HTTP request is still in flight: the rebuild resets
// the mutable isLiked field to post.wasLikedByMe (false).
await tester.pump();
});
// The widget must propagate the NEW value synchronously, before the
// request completes. A broken implementation that reads the mutable
// isLiked field after the await has not called this at all yet.
expect(profileCubit.likeUpdates, hasLength(1));
expect(profileCubit.likeUpdates.single.post.id, expectedPost.id);
expect(profileCubit.likeUpdates.single.wasLikedByMe, isTrue);
likeCompleter.complete();
await tester.pump();
// Issue #582, P1: exactly once, with the NEW value.
expect(profileCubit.likeUpdates, hasLength(1));
expect(profileCubit.likeUpdates.single.wasLikedByMe, isTrue);
},
);
testWidgets(
'liking a post stores the new like value and keeps the heart and counter after rebuild',
(tester) async {
final feedCubit = MockFeedCubit();
final likeCompleter = Completer<void>();
when(feedCubit.likePost(any)).thenAnswer((_) => likeCompleter.future);
final profileCubit = ProfileCubit(
profileRepository: MockProfileRepository(),
chatRepository: MockChatRepository(),
consultantRepository: MockConsultantRepository(),
);
addTearDown(profileCubit.close);
profileCubit.emit(loadedState());
await mockNetworkImagesFor(() async {
await tester.pumpWidget(
wrap(profileCubit: profileCubit, feedCubit: feedCubit),
);
await tester.pumpAndSettle();
final likeButton = find.byIcon(Icons.favorite_border_rounded);
await tester.ensureVisible(likeButton);
await tester.pump();
await tester.tap(likeButton);
// A frame while the HTTP request is still in flight: the build resets
// isLiked/totalLikes from the post unless the new value was stored.
await tester.pump();
});
expect(find.byIcon(Icons.favorite_rounded), findsOneWidget);
expect(find.text('11'), findsOneWidget);
likeCompleter.complete();
await tester.pump();
final state = profileCubit.state as ProfileStateLoaded;
expect(state.blogPosts.single.wasLikedByMe, isTrue);
expect(state.blogPosts.single.totalLikes, 11);
expect(find.byIcon(Icons.favorite_rounded), findsOneWidget);
expect(find.text('11'), findsOneWidget);
},
);
});
}
class _RecordingProfileCubit extends ProfileCubit {
_RecordingProfileCubit({
required super.profileRepository,
required super.chatRepository,
required super.consultantRepository,
});
final List<({FeedBlogPostModel post, bool wasLikedByMe})> likeUpdates = [];
@override
void updateFeedBlogPostList(FeedBlogPostModel post, bool wasLikedByMe) {
likeUpdates.add((post: post, wasLikedByMe: wasLikedByMe));
super.updateFeedBlogPostList(post, wasLikedByMe);
}
}