feat(tests): fixed feed tests failing and added tests for my_diets, my_plans and recipes

This commit is contained in:
misha
2025-11-28 00:46:25 +03:00
parent 626f74d20d
commit 8917f54e7b
14 changed files with 2807 additions and 103 deletions

View File

@@ -0,0 +1,256 @@
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/plan_pagination_model.dart';
import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_cubit.dart';
import 'package:eatvio_app/features/my_plans/repositories/my_diets_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'my_plans_cubit_test.mocks.dart';
@GenerateNiceMocks([MockSpec<MyPlansRepository>()])
void main() {
group('MyPlansCubit', () {
MyPlansCubit? myPlansCubit;
late MockMyPlansRepository mockMyPlansRepository;
final testPlan = PlanModel(
id: 1,
slug: 'test-plan',
name: 'Test Plan',
image: 'https://someurl.com/img.jpg',
duration: 30,
state: 'active',
type: const PlanType(fit: true, slim: false, behavior: false, wellness: false),
details: 'Test plan description',
packetsCount: 1,
author: const Author(authorSlug: '', authorName: '', authorProfileIcon: '', authorIsMe: false),
totalLikes: 1,
totalViews: 1,
totalComments: 1,
isFavorite: false,
minPriceOfOptions: 100.0,
maxPriceOfOptions: 500.0,
wasLikedByMe: false,
);
final testPlansPagination = PlanPaginationModel(
data: [testPlan],
links: const 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, totalMinPrice: 100, totalMaxPrice: 500),
);
setUp(() {
mockMyPlansRepository = MockMyPlansRepository();
});
tearDown(() async {
if (myPlansCubit != null && !myPlansCubit!.isClosed) {
await Future.delayed(const Duration(milliseconds: 100));
myPlansCubit!.close();
myPlansCubit = null;
}
});
test('начальное состояние - empty state', () {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
expect(myPlansCubit!.state.activePlans, isEmpty);
expect(myPlansCubit!.state.draftPlans, isEmpty);
expect(myPlansCubit!.state.isLoading, false);
expect(myPlansCubit!.state.selectedStateIndex, 0);
});
test('loadAllPlans - загружает все планы', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.getPlans(
page: 1,
query: null,
types: null,
duration: null,
minPrice: null,
maxPrice: null,
)).thenAnswer((_) async => testPlansPagination);
await myPlansCubit!.loadAllPlans();
await Future.delayed(const Duration(milliseconds: 200));
expect(myPlansCubit!.state.activePlans.length, 1);
expect(myPlansCubit!.state.draftPlans.length, 1);
expect(myPlansCubit!.state.isLoading, false);
});
test('loadPlans - загружает активные планы', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.getPlans(
page: 1,
query: null,
types: null,
duration: null,
minPrice: null,
maxPrice: null,
)).thenAnswer((_) async => testPlansPagination);
await myPlansCubit!.loadPlans();
await Future.delayed(const Duration(milliseconds: 200));
expect(myPlansCubit!.state.activePlans.length, 1);
});
test('changeSelectedStateIndex - меняет выбранный индекс состояния', () {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
myPlansCubit!.changeSelectedStateIndex(1);
expect(myPlansCubit!.state.selectedStateIndex, 1);
myPlansCubit!.changeSelectedStateIndex(0);
expect(myPlansCubit!.state.selectedStateIndex, 0);
});
test('changeTypeFilter - меняет фильтр типа для активных планов', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.getPlans(
page: 1,
query: null,
types: 'fit',
duration: null,
minPrice: null,
maxPrice: null,
)).thenAnswer((_) async => testPlansPagination);
myPlansCubit!.changeTypeFilter(1);
await Future.delayed(const Duration(milliseconds: 1200));
expect(myPlansCubit!.state.activeFilterState.typeIndex, 1);
});
test('changeDurationFilter - меняет фильтр длительности', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.getPlans(
page: 1,
query: null,
types: null,
duration: 7,
minPrice: null,
maxPrice: null,
)).thenAnswer((_) async => testPlansPagination);
myPlansCubit!.changeDurationFilter(1);
await Future.delayed(const Duration(milliseconds: 1200));
expect(myPlansCubit!.state.activeFilterState.durationIndex, 1);
});
test('changePriceFilter - меняет фильтр цены', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.getPlans(
page: 1,
query: null,
types: null,
duration: null,
minPrice: 100,
maxPrice: 500,
)).thenAnswer((_) async => testPlansPagination);
myPlansCubit!.changePriceFilter(100, 500);
await Future.delayed(const Duration(milliseconds: 1200));
expect(myPlansCubit!.state.activeFilterState.priceFilter.$1, 100);
expect(myPlansCubit!.state.activeFilterState.priceFilter.$2, 500);
});
test('deletePlan - удаляет план успешно', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.deletePlan('test-plan-slug')).thenAnswer((_) async => Future.value());
when(mockMyPlansRepository.getPlans(
page: 1,
query: null,
types: null,
duration: null,
minPrice: null,
maxPrice: null,
)).thenAnswer((_) async => testPlansPagination);
final result = await myPlansCubit!.deletePlan('test-plan-slug');
await Future.delayed(const Duration(milliseconds: 200));
expect(result, true);
verify(mockMyPlansRepository.deletePlan('test-plan-slug')).called(1);
});
test('deletePlan - обрабатывает ошибку при удалении', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.deletePlan('test-plan-slug')).thenThrow(Exception('Network error'));
final result = await myPlansCubit!.deletePlan('test-plan-slug');
expect(result, false);
expect(myPlansCubit!.state.error, isNotNull);
});
test('unpublish - снимает с публикации план успешно', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.unpublish('test-plan-slug')).thenAnswer((_) async => Future.value());
final result = await myPlansCubit!.unpublish('test-plan-slug');
expect(result, true);
verify(mockMyPlansRepository.unpublish('test-plan-slug')).called(1);
});
test('unpublish - обрабатывает ошибку при снятии с публикации', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.unpublish('test-plan-slug')).thenThrow(Exception('Network error'));
final result = await myPlansCubit!.unpublish('test-plan-slug');
expect(result, false);
});
test('_loadActivePlans - обрабатывает ошибку', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.getPlans(
page: 1,
query: null,
types: null,
duration: null,
minPrice: null,
maxPrice: null,
)).thenThrow(Exception('Network error'));
await myPlansCubit!.loadPlans();
await Future.delayed(const Duration(milliseconds: 200));
expect(myPlansCubit!.state.error, isNotNull);
});
test('_loadActivePlans - устанавливает ценовой фильтр из мета', () async {
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
when(mockMyPlansRepository.getPlans(
page: 1,
query: null,
types: null,
duration: null,
minPrice: null,
maxPrice: null,
)).thenAnswer((_) async => testPlansPagination);
await myPlansCubit!.loadPlans();
await Future.delayed(const Duration(milliseconds: 200));
expect(myPlansCubit!.state.minActivePlanPrice, 100);
expect(myPlansCubit!.state.maxActivePlanPrice, 500);
});
});
}

View File

@@ -0,0 +1,195 @@
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/custom_outlined_button.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/my_plans/presentation/cubit/my_plans_cubit.dart';
import 'package:eatvio_app/features/my_plans/presentation/cubit/my_plans_state.dart';
import 'package:eatvio_app/features/my_plans/presentation/widgets/my_plan_widget.dart';
import 'package:eatvio_app/features/my_plans/repositories/my_diets_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_portal/flutter_portal.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'basic_widget_test.mocks.dart';
@GenerateNiceMocks([MockSpec<MyPlansRepository>()])
void main() {
group('MyPlans Basic Widget Tests', () {
late MockMyPlansRepository mockMyPlansRepository;
late MyPlansCubit myPlansCubit;
final testPlan = PlanModel(
id: 1,
slug: 'test-plan',
name: 'Test Plan',
image: 'test-image.jpg',
duration: 30,
state: 'active',
type: const PlanType(fit: true, slim: false, behavior: false, wellness: false),
details: 'Test plan description',
packetsCount: 1,
author: const Author(authorSlug: '', authorName: '', authorProfileIcon: '', authorIsMe: false),
totalLikes: 1,
totalViews: 1,
totalComments: 1,
isFavorite: false,
minPriceOfOptions: 100.0,
maxPriceOfOptions: 500.0,
wasLikedByMe: false,
packet1Options: null,
);
setUp(() async {
await sl.reset();
dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost');
mockMyPlansRepository = MockMyPlansRepository();
myPlansCubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
sl.registerLazySingleton<AppConfig>(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost'));
});
tearDown(() async {
await Future.delayed(const Duration(milliseconds: 100));
if (!myPlansCubit.isClosed) {
myPlansCubit.close();
}
});
Widget createTestWidget(Widget child, {bool wrapInScaffold = true}) {
final widget = BlocProvider<MyPlansCubit>(
create: (context) => myPlansCubit,
child: Portal(
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,
);
}
testWidgets('should create MyPlansCubit successfully', (WidgetTester tester) async {
// Arrange & Act
final cubit = MyPlansCubit(myPlansRepository: mockMyPlansRepository);
// Assert
expect(cubit, isA<MyPlansCubit>());
expect(cubit.state.activePlans, isEmpty);
cubit.close();
});
testWidgets('should display MyPlanWidget with plan name', (WidgetTester tester) async {
// Arrange
myPlansCubit.emit(MyPlansState(selectedStateIndex: 0));
final widget = MyPlanWidget(plan: testPlan);
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump(const Duration(milliseconds: 100));
// Assert
expect(find.text('Test Plan'), findsOneWidget);
expect(find.byType(MyPlanWidget), findsOneWidget);
});
testWidgets('should display MyPlanWidget with description when details are present', (WidgetTester tester) async {
// Arrange
myPlansCubit.emit(MyPlansState(selectedStateIndex: 0));
final widget = MyPlanWidget(plan: testPlan);
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump(const Duration(milliseconds: 100));
// Assert
expect(find.text('Test Plan'), findsOneWidget);
expect(find.byType(MyPlanWidget), findsOneWidget);
});
testWidgets('should display MyPlanWidget with price', (WidgetTester tester) async {
// Arrange
myPlansCubit.emit(MyPlansState(selectedStateIndex: 0));
final widget = MyPlanWidget(plan: testPlan);
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump(const Duration(milliseconds: 100));
// Assert
expect(find.text('Test Plan'), findsOneWidget);
expect(find.byType(MyPlanWidget), findsOneWidget);
});
testWidgets('should display MyPlanWidget buttons', (WidgetTester tester) async {
// Arrange
myPlansCubit.emit(MyPlansState(selectedStateIndex: 0));
final widget = MyPlanWidget(plan: testPlan);
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump(const Duration(milliseconds: 100));
// Assert
expect(find.byType(MyPlanWidget), findsOneWidget);
expect(find.byType(CustomOutlinedButton), findsWidgets);
});
testWidgets('should display MyPlanWidget structure correctly', (WidgetTester tester) async {
// Arrange
myPlansCubit.emit(MyPlansState(selectedStateIndex: 0));
final widget = MyPlanWidget(plan: testPlan);
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump(const Duration(milliseconds: 100));
// Assert
expect(find.byType(MyPlanWidget), findsOneWidget);
expect(find.text('Test Plan'), findsOneWidget);
expect(find.byType(CustomOutlinedButton), findsWidgets);
});
testWidgets('should display MyPlanWidget with empty details', (WidgetTester tester) async {
// Arrange
myPlansCubit.emit(MyPlansState(selectedStateIndex: 0));
final planWithoutDetails = testPlan.copyWith(details: '');
final widget = MyPlanWidget(plan: planWithoutDetails);
// Act
await tester.pumpWidget(createTestWidget(widget));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump(const Duration(milliseconds: 100));
// Assert
expect(find.text('Test Plan'), findsOneWidget);
expect(find.byType(MyPlanWidget), findsOneWidget);
});
});
}