feat(tests): test coverage is 69.2

This commit is contained in:
misha
2026-01-21 09:19:41 +03:00
parent 775d4fb80f
commit f6809a06b3
16 changed files with 5274 additions and 333 deletions

View File

@@ -606,11 +606,7 @@ void main() {
await Future.delayed(const Duration(milliseconds: 200));
// Мокаем карту с isDefault = true
final cardWithDefault = CardModel(
id: 1,
cardNumber: '1234',
isDefault: true,
);
final cardWithDefault = CardModel(id: 1, cardNumber: '1234', isDefault: true);
when(mockCardsRepository.getCards()).thenAnswer((_) async => [cardWithDefault]);
await chatRoomCubit.checkCards();
@@ -635,11 +631,7 @@ void main() {
await Future.delayed(const Duration(milliseconds: 200));
// Мокаем карту с isDefault = false
final cardWithoutDefault = CardModel(
id: 1,
cardNumber: '1234',
isDefault: false,
);
final cardWithoutDefault = CardModel(id: 1, cardNumber: '1234', isDefault: false);
when(mockCardsRepository.getCards()).thenAnswer((_) async => [cardWithoutDefault]);
await chatRoomCubit.checkCards();
@@ -1072,5 +1064,300 @@ void main() {
// Не должно вызывать getChatMessages для страницы 2
verifyNever(mockChatRepository.getChatMessages(uuid, 2));
});
test('resendMessage - не делает ничего если сообщение не найдено', () async {
const uuid = 'room-uuid';
const messageUuid = 'non-existent-uuid';
final initialMessages = ChatMessagesModel(
messagesList: [
ChatMessageModel(
id: 1,
data: 'Test message',
mediaData: null,
authorId: 1,
updatedAt: DateTime.now(),
isRead: false,
isCurrentUserAuthor: true,
roomId: 'chat-id',
),
],
meta: const ChatMetaModel(lastPage: 1),
);
when(mockChatRepository.getChatRoom(uuid)).thenAnswer((_) async => testChatRoom);
when(mockChatRepository.getChatMessages(uuid, 1)).thenAnswer((_) async => initialMessages);
when(mockWsManager.client).thenReturn(null);
when(mockWsManager.initPrivateDirectChatChannel(any)).thenAnswer((_) async => Future.value());
when(mockWsManager.subscribeDirectChatChannel()).thenReturn(null);
when(mockWsManager.directChatStream).thenReturn(null);
when(mockWsManager.clientTypingStream).thenReturn(null);
when(mockChatRepository.getChosenPlan(id: anyNamed('id'))).thenAnswer((_) async => throw Exception('No plan'));
await chatRoomCubit.initChat(uuid);
await Future.delayed(const Duration(milliseconds: 200));
await chatRoomCubit.resendMessage(uuid: messageUuid, userSlug: 'user-1');
await Future.delayed(const Duration(milliseconds: 100));
verifyNever(mockChatRepository.sendMessage(data: anyNamed('data'), files: anyNamed('files'), slug: anyNamed('slug')));
});
test('initChat - вызывает checkCards если consultantId == sender.id', () async {
const uuid = 'room-uuid';
const planId = 123;
final chatRoomWithPlan = testChatRoom.copyWith(chosenPlanId: planId);
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,
author: Author(authorSlug: 'author', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false),
totalLikes: 10,
totalViews: 100,
totalComments: 5,
isFavorite: false,
minPriceOfOptions: 1000,
maxPriceOfOptions: 2000,
wasLikedByMe: false,
);
final chosenPlan = ChosenPlanModel(
id: planId,
optionType: 'options1',
startDate: DateTime.now(),
chosenPlanState: ChosenPlanStateEnum.stateStarted,
chatId: 'chat-1',
consultantId: 1, // совпадает с sender.id
plan: testPlan,
);
when(mockChatRepository.getChatRoom(uuid)).thenAnswer((_) async => chatRoomWithPlan);
when(mockChatRepository.getChatMessages(uuid, 1)).thenAnswer((_) async => testChatMessages);
when(mockChatRepository.getChosenPlan(id: planId)).thenAnswer((_) async => chosenPlan);
when(mockWsManager.client).thenReturn(null);
when(mockWsManager.initPrivateDirectChatChannel(any)).thenAnswer((_) async => Future.value());
when(mockWsManager.subscribeDirectChatChannel()).thenReturn(null);
when(mockWsManager.directChatStream).thenReturn(null);
when(mockWsManager.clientTypingStream).thenReturn(null);
when(mockCardsRepository.getCards()).thenAnswer((_) async => []);
await chatRoomCubit.initChat(uuid);
await Future.delayed(const Duration(milliseconds: 200));
verify(mockCardsRepository.getCards()).called(1);
});
test('initChat - не вызывает checkCards если consultantId != sender.id', () async {
const uuid = 'room-uuid';
const planId = 123;
final chatRoomWithPlan = testChatRoom.copyWith(chosenPlanId: planId);
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,
author: Author(authorSlug: 'author', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false),
totalLikes: 10,
totalViews: 100,
totalComments: 5,
isFavorite: false,
minPriceOfOptions: 1000,
maxPriceOfOptions: 2000,
wasLikedByMe: false,
);
final chosenPlan = ChosenPlanModel(
id: planId,
optionType: 'options1',
startDate: DateTime.now(),
chosenPlanState: ChosenPlanStateEnum.stateStarted,
chatId: 'chat-1',
consultantId: 2, // не совпадает с sender.id (1)
plan: testPlan,
);
when(mockChatRepository.getChatRoom(uuid)).thenAnswer((_) async => chatRoomWithPlan);
when(mockChatRepository.getChatMessages(uuid, 1)).thenAnswer((_) async => testChatMessages);
when(mockChatRepository.getChosenPlan(id: planId)).thenAnswer((_) async => chosenPlan);
when(mockWsManager.client).thenReturn(null);
when(mockWsManager.initPrivateDirectChatChannel(any)).thenAnswer((_) async => Future.value());
when(mockWsManager.subscribeDirectChatChannel()).thenReturn(null);
when(mockWsManager.directChatStream).thenReturn(null);
when(mockWsManager.clientTypingStream).thenReturn(null);
await chatRoomCubit.initChat(uuid);
await Future.delayed(const Duration(milliseconds: 200));
verifyNever(mockCardsRepository.getCards());
});
test('choseStartPlanDate - обрабатывает ошибку', () async {
const uuid = 'room-uuid';
const planId = 123;
final chatRoomWithPlan = testChatRoom.copyWith(chosenPlanId: planId);
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,
author: Author(authorSlug: 'author', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false),
totalLikes: 10,
totalViews: 100,
totalComments: 5,
isFavorite: false,
minPriceOfOptions: 1000,
maxPriceOfOptions: 2000,
wasLikedByMe: false,
);
final chosenPlan = ChosenPlanModel(
id: planId,
optionType: 'options1',
startDate: DateTime(2024, 1, 1),
chosenPlanState: ChosenPlanStateEnum.statePendingPayment,
chatId: 'chat-1',
consultantId: 1,
plan: testPlan,
);
when(mockChatRepository.getChatRoom(uuid)).thenAnswer((_) async => chatRoomWithPlan);
when(mockChatRepository.getChatMessages(uuid, 1)).thenAnswer((_) async => testChatMessages);
when(mockChatRepository.getChosenPlan(id: planId)).thenAnswer((_) async => chosenPlan);
when(mockChatRepository.choseStartPlanDate(id: planId, date: anyNamed('date'))).thenThrow(Exception('Error'));
when(mockWsManager.client).thenReturn(null);
when(mockWsManager.initPrivateDirectChatChannel(any)).thenAnswer((_) async => Future.value());
when(mockWsManager.subscribeDirectChatChannel()).thenReturn(null);
when(mockWsManager.directChatStream).thenReturn(null);
when(mockWsManager.clientTypingStream).thenReturn(null);
await chatRoomCubit.initChat(uuid);
await Future.delayed(const Duration(milliseconds: 200));
final result = await chatRoomCubit.choseStartPlanDate(DateTime(2024, 1, 15));
expect(result, false);
});
test('checkCards - обрабатывает ошибку', () async {
const uuid = 'room-uuid';
when(mockChatRepository.getChatRoom(uuid)).thenAnswer((_) async => testChatRoom);
when(mockChatRepository.getChatMessages(uuid, 1)).thenAnswer((_) async => testChatMessages);
when(mockWsManager.client).thenReturn(null);
when(mockWsManager.initPrivateDirectChatChannel(any)).thenAnswer((_) async => Future.value());
when(mockWsManager.subscribeDirectChatChannel()).thenReturn(null);
when(mockWsManager.directChatStream).thenReturn(null);
when(mockWsManager.clientTypingStream).thenReturn(null);
when(mockChatRepository.getChosenPlan(id: anyNamed('id'))).thenAnswer((_) async => throw Exception('No plan'));
await chatRoomCubit.initChat(uuid);
await Future.delayed(const Duration(milliseconds: 200));
when(mockCardsRepository.getCards()).thenThrow(Exception('Error'));
await chatRoomCubit.checkCards();
await Future.delayed(const Duration(milliseconds: 100));
// Не должно быть исключений, ошибка должна быть обработана
expect(chatRoomCubit.state, isA<ChatRoomStateLoaded>());
});
test('deleteMessage - не делает ничего если state не loaded', () {
const uuid = 'message-uuid';
chatRoomCubit.deleteMessage(uuid);
// Не должно быть исключений
expect(chatRoomCubit.state, isA<ChatRoomStateLoading>());
});
test('resendMessage - не делает ничего если state не loaded', () async {
const uuid = 'message-uuid';
await chatRoomCubit.resendMessage(uuid: uuid, userSlug: 'user-1');
verifyNever(mockChatRepository.sendMessage(data: anyNamed('data'), files: anyNamed('files'), slug: anyNamed('slug')));
});
test('loadNextPage - обновляет currentPage после успешной загрузки', () async {
const uuid = 'room-uuid';
final initialMessages = ChatMessagesModel(
messagesList: [
ChatMessageModel(
id: 1,
data: 'Initial message',
mediaData: null,
authorId: 1,
updatedAt: DateTime.now(),
isRead: false,
isCurrentUserAuthor: true,
roomId: 'chat-id',
),
],
meta: const ChatMetaModel(lastPage: 2),
);
final nextPageMessages = ChatMessagesModel(
messagesList: [
ChatMessageModel(
id: 2,
data: 'Next page message',
mediaData: null,
authorId: 1,
updatedAt: DateTime.now(),
isRead: false,
isCurrentUserAuthor: true,
roomId: 'chat-id',
),
],
meta: const ChatMetaModel(lastPage: 2),
);
when(mockChatRepository.getChatRoom(uuid)).thenAnswer((_) async => testChatRoom);
when(mockChatRepository.getChatMessages(uuid, 1)).thenAnswer((_) async => initialMessages);
when(mockWsManager.client).thenReturn(null);
when(mockWsManager.initPrivateDirectChatChannel(any)).thenAnswer((_) async => Future.value());
when(mockWsManager.subscribeDirectChatChannel()).thenReturn(null);
when(mockWsManager.directChatStream).thenReturn(null);
when(mockWsManager.clientTypingStream).thenReturn(null);
when(mockChatRepository.getChosenPlan(id: anyNamed('id'))).thenAnswer((_) async => throw Exception('No plan'));
await chatRoomCubit.initChat(uuid);
await Future.delayed(const Duration(milliseconds: 200));
expect(chatRoomCubit.currentPage, 1);
when(mockChatRepository.getChatMessages(uuid, 2)).thenAnswer((_) async => nextPageMessages);
await chatRoomCubit.loadNextPage(uuid);
await Future.delayed(const Duration(milliseconds: 200));
expect(chatRoomCubit.currentPage, 2);
});
test('loadNextPage - не загружает если state не loaded', () async {
const uuid = 'room-uuid';
// loadNextPage проверяет lastPage, который не инициализирован до initChat
// Метод выбросит исключение, но мы просто проверяем, что getChatMessages не вызывается
try {
await chatRoomCubit.loadNextPage(uuid);
} catch (e) {
// Ожидаем исключение, так как lastPage не инициализирован
expect(e, isNotNull);
}
verifyNever(mockChatRepository.getChatMessages(any, any));
});
});
}

View File

@@ -1,9 +1,13 @@
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/features/create_diet/presentation/cubit/create_diet_cubit.dart';
import 'package:eatvio_app/features/create_diet/repositories/create_diet_repository.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/glossary/models/glossary_model.dart';
import 'package:eatvio_app/features/glossary/repositories/glossary_repository.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
@@ -19,7 +23,13 @@ void main() {
late MockProfileRepository profileRepository;
late MockGlossaryRepository glossaryRepository;
setUp(() {
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'));
dietRepository = MockCreateDietRepository();
profileRepository = MockProfileRepository();
glossaryRepository = MockGlossaryRepository();
@@ -335,5 +345,213 @@ void main() {
cubit.removePortion(day: 0, meal: 0, portionIndex: 0);
expect(cubit.state.dietData.dailySchedule?[0][0].length, 0);
});
test('setInitialData returns early when diet is null', () async {
await cubit.setInitialData(null);
expect(cubit.state.isDietBeingEdited, false);
expect(cubit.dietId, isNull);
});
test('setInitialData initializes data for editing diet', () async {
const testDiet = Diet(
id: 1,
slug: 'test-diet',
name: 'Test Diet',
image: 'test-image.jpg',
duration: 7,
state: DietState.active,
type: DietType(light: true, veg: false, carb: false, meat: false),
details: 'Test details',
dailySchedule: {
1: {
1: {1: DailySchedule(name: 'Apple', portion: Portion.grams, quantity: 100, dailyNutrition: null, productNutritionalValueId: null)},
},
},
author: Author(authorSlug: 'test-author', authorName: 'Test Author', authorProfileIcon: '', authorIsMe: false),
totalLikes: 0,
totalViews: 0,
totalComments: 0,
wasLikedByMe: false,
isFavorite: false,
dailyNutrition: [],
);
final dailyScheduleWithNutrition = {
1: {
1: {1: const DailySchedule(name: 'Apple', portion: Portion.grams, quantity: 100, dailyNutrition: null, productNutritionalValueId: null)},
},
};
when(dietRepository.getDietPortionsNutrition(1)).thenAnswer((_) async => dailyScheduleWithNutrition);
await cubit.setInitialData(testDiet);
expect(cubit.dietId, 1);
expect(cubit.state.isDietBeingEdited, true);
expect(cubit.state.dietData.name, 'Test Diet');
expect(cubit.state.dietData.details, 'Test details');
expect(cubit.state.dietData.duration, 7);
expect(cubit.state.dietData.type['light'], true);
expect(cubit.state.dietData.type['veg'], false);
verify(dietRepository.getDietPortionsNutrition(1)).called(1);
});
test('createDiet validates empty name', () async {
cubit.setName('');
cubit.setDetails('Test Description');
cubit.setDuration(0);
cubit.setDietState(DietState.active);
const portion = DailySchedule(
name: 'Apple',
portion: Portion.grams,
quantity: 100,
dailyNutrition: DailyNutrition(energy: 52.0, proteins: 0.3, fats: 0.2, carbohydrates: 14.0),
productNutritionalValueId: '1',
);
cubit.addPortion(dayIndex: 0, mealIndex: 0, portion: portion);
final image = XFile('test_image.jpg');
cubit.setImage(image);
final result = await cubit.createDiet();
expect(result, 'validation');
expect(cubit.state.dietNameError, 'Поле не заполнено');
});
test('createDiet validates empty details', () async {
cubit.setName('Test Diet');
cubit.setDetails('');
cubit.setDuration(0);
cubit.setDietState(DietState.active);
const portion = DailySchedule(
name: 'Apple',
portion: Portion.grams,
quantity: 100,
dailyNutrition: DailyNutrition(energy: 52.0, proteins: 0.3, fats: 0.2, carbohydrates: 14.0),
productNutritionalValueId: '1',
);
cubit.addPortion(dayIndex: 0, mealIndex: 0, portion: portion);
final image = XFile('test_image.jpg');
cubit.setImage(image);
final result = await cubit.createDiet();
expect(result, 'validation');
expect(cubit.state.dietDescriptionError, 'Поле не заполнено');
});
test('createDiet validates missing duration', () async {
cubit.setName('Test Diet');
cubit.setDetails('Test Description');
cubit.setDietState(DietState.active);
const portion = DailySchedule(
name: 'Apple',
portion: Portion.grams,
quantity: 100,
dailyNutrition: DailyNutrition(energy: 52.0, proteins: 0.3, fats: 0.2, carbohydrates: 14.0),
productNutritionalValueId: '1',
);
cubit.addPortion(dayIndex: 0, mealIndex: 0, portion: portion);
final image = XFile('test_image.jpg');
cubit.setImage(image);
final result = await cubit.createDiet();
expect(result, 'validation');
expect(cubit.state.dietDurationError, 'Срок диеты не выбран');
});
test('createDiet validates missing state', () async {
cubit.setName('Test Diet');
cubit.setDetails('Test Description');
cubit.setDuration(0);
const portion = DailySchedule(
name: 'Apple',
portion: Portion.grams,
quantity: 100,
dailyNutrition: DailyNutrition(energy: 52.0, proteins: 0.3, fats: 0.2, carbohydrates: 14.0),
productNutritionalValueId: '1',
);
cubit.addPortion(dayIndex: 0, mealIndex: 0, portion: portion);
final image = XFile('test_image.jpg');
cubit.setImage(image);
final result = await cubit.createDiet();
expect(result, 'validation');
expect(cubit.state.dietStateError, 'Статус диеты не выбран');
});
test('createDiet validates missing image', () async {
cubit.setName('Test Diet');
cubit.setDetails('Test Description');
cubit.setDuration(0);
cubit.setDietState(DietState.active);
const portion = DailySchedule(
name: 'Apple',
portion: Portion.grams,
quantity: 100,
dailyNutrition: DailyNutrition(energy: 52.0, proteins: 0.3, fats: 0.2, carbohydrates: 14.0),
productNutritionalValueId: '1',
);
cubit.addPortion(dayIndex: 0, mealIndex: 0, portion: portion);
final result = await cubit.createDiet();
expect(result, 'validation');
expect(cubit.state.dietImageError, 'Не добавлена обложка');
});
test('createDiet validates empty daily schedule', () async {
cubit.setName('Test Diet');
cubit.setDetails('Test Description');
cubit.setDuration(0);
cubit.setDietState(DietState.active);
final image = XFile('test_image.jpg');
cubit.setImage(image);
final result = await cubit.createDiet();
expect(result, 'validation');
expect(cubit.state.dailyScheduleErrors[0], 'Добавьте продукты');
});
test('pasteCopiedDay validates day when pasting', () {
cubit.setDuration(0);
const portion = DailySchedule(
name: 'Apple',
portion: Portion.grams,
quantity: 100,
dailyNutrition: DailyNutrition(energy: 52.0, proteins: 0.3, fats: 0.2, carbohydrates: 14.0),
productNutritionalValueId: '1',
);
cubit.addPortion(dayIndex: 0, mealIndex: 0, portion: portion);
cubit.copyDay(0);
cubit.pasteCopiedDay(1);
expect(cubit.state.dietData.dailySchedule?[1][0].length, 1);
expect(cubit.state.dailyScheduleErrors[1], '');
});
test('_isDayValid returns false when day is empty', () {
cubit.setDuration(0);
final isValid = cubit.state.dietData.dailySchedule?[0].every((meal) => meal.isEmpty) ?? false;
expect(isValid, true);
});
test('_isDayValid returns true when day has portions', () {
cubit.setDuration(0);
const portion = DailySchedule(
name: 'Apple',
portion: Portion.grams,
quantity: 100,
dailyNutrition: DailyNutrition(energy: 52.0, proteins: 0.3, fats: 0.2, carbohydrates: 14.0),
productNutritionalValueId: '1',
);
cubit.addPortion(dayIndex: 0, mealIndex: 0, portion: portion);
final isValid = cubit.state.dietData.dailySchedule?[0].every((meal) => meal.isEmpty) ?? true;
expect(isValid, false);
});
});
}

View File

@@ -621,5 +621,105 @@ void main() {
cubit.setOptionContent('Item 2', 1);
expect(cubit.state.planData.options[0].items.length, 2);
});
test('validateTitlesOfAllFilledOptions - возвращает true когда selectedOptionIndex == null и все опции валидны', () {
cubit.setSelectedOptionIndex(null);
cubit.setOptionTitle('Valid Title 1');
cubit.setSelectedOptionIndex(0);
cubit.setOptionTitle('Valid Title 1');
cubit.setSelectedOptionIndex(1);
cubit.setOptionTitle('Valid Title 2');
cubit.setSelectedOptionIndex(2);
cubit.setOptionTitle('Valid Title 3');
cubit.setSelectedOptionIndex(null);
final result = cubit.validateTitlesOfAllFilledOptions();
expect(result, true);
});
test('validateTitlesOfAllFilledOptions - возвращает false когда selectedOptionIndex == null и опция 0 невалидна', () {
cubit.setSelectedOptionIndex(0);
cubit.setOptionTitle('AB'); // невалидное название
cubit.setSelectedOptionIndex(null);
final result = cubit.validateTitlesOfAllFilledOptions();
expect(result, false);
});
test('validateDescriptionsOfAllOptions - возвращает true когда selectedOptionIndex == null и все описания валидны', () {
cubit.setSelectedOptionIndex(0);
cubit.setOptionDescription('Valid Description 1');
cubit.setSelectedOptionIndex(1);
cubit.setOptionDescription('Valid Description 2');
cubit.setSelectedOptionIndex(2);
cubit.setOptionDescription('Valid Description 3');
cubit.setSelectedOptionIndex(null);
final result = cubit.validateDescriptionsOfAllOptions();
expect(result, true);
});
test('validateDescriptionsOfAllOptions - возвращает false когда selectedOptionIndex == null и опция 0 невалидна', () {
cubit.setSelectedOptionIndex(0);
cubit.setOptionDescription('AB'); // невалидное описание
cubit.setSelectedOptionIndex(null);
final result = cubit.validateDescriptionsOfAllOptions();
expect(result, false);
});
test('validateItemsOfAllFilledOptions - возвращает true когда selectedOptionIndex == null и все items валидны', () {
cubit.setSelectedOptionIndex(0);
cubit.setOptionContent('Valid Item 1', 0);
cubit.setSelectedOptionIndex(1);
cubit.setOptionContent('Valid Item 2', 0);
cubit.setSelectedOptionIndex(2);
cubit.setOptionContent('Valid Item 3', 0);
cubit.setSelectedOptionIndex(null);
final result = cubit.validateItemsOfAllFilledOptions();
expect(result, true);
});
test('validateItemsOfAllFilledOptions - возвращает false когда selectedOptionIndex == null и опция 0 имеет пустые items', () {
cubit.setSelectedOptionIndex(0);
// items пустые
cubit.setSelectedOptionIndex(null);
final result = cubit.validateItemsOfAllFilledOptions();
expect(result, false);
});
test('validatePriceOfAllFilledOptions - возвращает true когда все цены валидны', () {
cubit.setSelectedOptionIndex(0);
cubit.setPrice(1500.0);
cubit.setSelectedOptionIndex(1);
cubit.setPrice(2000.0);
cubit.setSelectedOptionIndex(2);
cubit.setPrice(2500.0);
final result = cubit.validatePriceOfAllFilledOptions();
expect(result, true);
});
test('validatePriceOfAllFilledOptions - возвращает false когда опция 1 имеет невалидную цену', () {
cubit.setSelectedOptionIndex(0);
cubit.setPrice(1500.0);
cubit.setSelectedOptionIndex(1);
cubit.setPrice(1000.0); // невалидная цена
cubit.setSelectedOptionIndex(2);
cubit.setPrice(2500.0);
final result = cubit.validatePriceOfAllFilledOptions();
expect(result, false);
});
test('setPlanType - не валидирует когда type.any((elem) => elem) == false', () {
cubit.setPlanType([false, false, false, false]);
expect(cubit.state.planData.type, [false, false, false, false]);
// Валидация не должна вызываться, так как все элементы false
});
});
}

View File

@@ -18,6 +18,8 @@ import 'diets_cubit_test.mocks.dart';
MockSpec<DietRepository>(),
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('DietsCubit', () {
DietsCubit? dietsCubit;
late MockFeedRepository mockFeedRepository;
@@ -805,6 +807,190 @@ void main() {
expect(dietsCubit!.state.dietsList[0].wasLikedByMe, false);
expect(dietsCubit!.state.dietsList[0].totalLikes, 10);
});
test('_changeDietLikeState - обновляет состояние лайка через stream', () async {
final likesStateSubject = BehaviorSubject<LikesState>();
when(mockDietRepository.dietLikeState).thenAnswer((_) => likesStateSubject.stream);
when(mockDietRepository.dietFavoriteState).thenAnswer((_) => BehaviorSubject<FavoriteState>());
when(mockDietRepository.dietCommentsState).thenAnswer((_) => BehaviorSubject<CommentsState>());
dietsCubit = DietsCubit(
feedRepository: mockFeedRepository,
dietsRepository: mockDietRepository,
);
const testDiet = Diet(
id: 1,
slug: 'test-diet',
name: 'Test Diet',
image: 'https://example.com/image.jpg',
duration: 7,
state: DietState.active,
type: DietType(veg: true, light: false, carb: false, meat: false),
details: 'Test details',
dailySchedule: {},
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,
dailyNutrition: [],
);
const dietsPagination = DietsPagination(
data: [testDiet],
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),
);
when(mockFeedRepository.getDiets(
query: anyNamed('query'),
types: anyNamed('types'),
duration: anyNamed('duration'),
sorting: anyNamed('sorting'),
)).thenAnswer((_) async => dietsPagination);
await dietsCubit!.loadDiets();
await Future.delayed(const Duration(milliseconds: 200));
// Эмитим новое состояние лайка
likesStateSubject.add(const LikesState(wasLikedByMe: true, totalLikes: 11, index: 0));
await Future.delayed(const Duration(milliseconds: 100));
expect(dietsCubit!.state.dietsList[0].wasLikedByMe, true);
expect(dietsCubit!.state.dietsList[0].totalLikes, 11);
await likesStateSubject.close();
});
test('_changeDietFavoriteState - обновляет состояние избранного через stream', () async {
final favoriteStateSubject = BehaviorSubject<FavoriteState>();
when(mockDietRepository.dietLikeState).thenAnswer((_) => BehaviorSubject<LikesState>());
when(mockDietRepository.dietFavoriteState).thenAnswer((_) => favoriteStateSubject.stream);
when(mockDietRepository.dietCommentsState).thenAnswer((_) => BehaviorSubject<CommentsState>());
dietsCubit = DietsCubit(
feedRepository: mockFeedRepository,
dietsRepository: mockDietRepository,
);
const testDiet = Diet(
id: 1,
slug: 'test-diet',
name: 'Test Diet',
image: 'https://example.com/image.jpg',
duration: 7,
state: DietState.active,
type: DietType(veg: true, light: false, carb: false, meat: false),
details: 'Test details',
dailySchedule: {},
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,
dailyNutrition: [],
);
const dietsPagination = DietsPagination(
data: [testDiet],
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),
);
when(mockFeedRepository.getDiets(
query: anyNamed('query'),
types: anyNamed('types'),
duration: anyNamed('duration'),
sorting: anyNamed('sorting'),
)).thenAnswer((_) async => dietsPagination);
await dietsCubit!.loadDiets();
await Future.delayed(const Duration(milliseconds: 200));
// Эмитим новое состояние избранного
favoriteStateSubject.add(const FavoriteState(isFavorite: true, index: 0));
await Future.delayed(const Duration(milliseconds: 100));
expect(dietsCubit!.state.dietsList[0].isFavorite, true);
await favoriteStateSubject.close();
});
test('_changeDietCommentsState - обновляет состояние комментариев через stream', () async {
final commentsStateSubject = BehaviorSubject<CommentsState>();
when(mockDietRepository.dietLikeState).thenAnswer((_) => BehaviorSubject<LikesState>());
when(mockDietRepository.dietFavoriteState).thenAnswer((_) => BehaviorSubject<FavoriteState>());
when(mockDietRepository.dietCommentsState).thenAnswer((_) => commentsStateSubject.stream);
dietsCubit = DietsCubit(
feedRepository: mockFeedRepository,
dietsRepository: mockDietRepository,
);
const testDiet = Diet(
id: 1,
slug: 'test-diet',
name: 'Test Diet',
image: 'https://example.com/image.jpg',
duration: 7,
state: DietState.active,
type: DietType(veg: true, light: false, carb: false, meat: false),
details: 'Test details',
dailySchedule: {},
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,
dailyNutrition: [],
);
const dietsPagination = DietsPagination(
data: [testDiet],
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),
);
when(mockFeedRepository.getDiets(
query: anyNamed('query'),
types: anyNamed('types'),
duration: anyNamed('duration'),
sorting: anyNamed('sorting'),
)).thenAnswer((_) async => dietsPagination);
await dietsCubit!.loadDiets();
await Future.delayed(const Duration(milliseconds: 200));
// Эмитим новое состояние комментариев
commentsStateSubject.add(const CommentsState(index: 0, totalComments: 6));
await Future.delayed(const Duration(milliseconds: 100));
expect(dietsCubit!.state.dietsList[0].totalComments, 6);
await commentsStateSubject.close();
});
test('loadNextPage - не загружает если lastPage не инициализирован', () async {
dietsCubit = DietsCubit(
feedRepository: mockFeedRepository,
dietsRepository: mockDietRepository,
);
// loadNextPage проверяет lastPage, который не инициализирован до loadDiets
// Метод выбросит исключение, но мы просто проверяем, что getDiets не вызывается
try {
await dietsCubit!.loadNextPage();
} catch (e) {
// Ожидаем исключение, так как lastPage не инициализирован
expect(e, isNotNull);
}
verifyNever(mockFeedRepository.getDiets(page: anyNamed('page'), query: anyNamed('query'), types: anyNamed('types'), duration: anyNamed('duration'), sorting: anyNamed('sorting')));
});
});
}

View File

@@ -18,6 +18,7 @@ import 'recipes_cubit_test.mocks.dart';
@GenerateNiceMocks([MockSpec<FeedRepository>(), MockSpec<RecipeRepository>(), MockSpec<AboutRecipeRepository>()])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('RecipesCubit', () {
RecipesCubit? recipesCubit;
late MockFeedRepository mockFeedRepository;
@@ -749,5 +750,219 @@ void main() {
expect(recipesCubit!.state.selectedTags.contains(2), isTrue);
expect(recipesCubit!.state.selectedTagsCounter, 1);
});
test('_changeRecipeLikeState - обновляет состояние лайка через stream', () async {
final likesStateSubject = BehaviorSubject<LikesState>();
when(mockAboutRecipeRepository.recipeLikeState).thenAnswer((_) => likesStateSubject.stream);
when(mockAboutRecipeRepository.recipeFavoriteState).thenAnswer((_) => BehaviorSubject<FavoriteState>());
when(mockAboutRecipeRepository.recipeCommentsState).thenAnswer((_) => BehaviorSubject<CommentsState>());
recipesCubit = RecipesCubit(
feedRepository: mockFeedRepository,
recipeRepository: mockRecipeRepository,
aboutRecipeRepository: mockAboutRecipeRepository,
);
const testRecipe = Recipe(
id: 1,
image: 'https://example.com/image.jpg',
state: 'active',
cookingTime: 30,
activeCookingTime: 15,
ingredients: [],
description: 'Test description',
steps: [],
videoUrl: null,
createdAt: null,
updatedAt: null,
title: 'Test Recipe',
type: 'main',
slug: 'test-recipe',
commentsCount: 5,
wasLikedByMe: false,
isFavorite: false,
calories: 300.0,
servings: 4,
likesCount: 10,
viewsCount: 100,
tags: [],
author: Author(authorSlug: 'author', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false, isEntitySubscribedByMe: null, authorPlaceInRating: null),
);
final testTags = [RecipeTag(id: 1, name: 'Tag 1', recipesCount: 10, createdAt: DateTime(2024, 1, 1), updatedAt: DateTime(2024, 1, 2))];
when(mockFeedRepository.getRecipes(tags: anyNamed('tags'), query: anyNamed('query'))).thenAnswer((_) async => [testRecipe]);
when(mockRecipeRepository.getRecipesTags()).thenAnswer((_) async => testTags);
await recipesCubit!.loadRecipesList();
await Future.delayed(const Duration(milliseconds: 200));
// Эмитим новое состояние лайка
likesStateSubject.add(const LikesState(wasLikedByMe: true, totalLikes: 11, index: 0));
await Future.delayed(const Duration(milliseconds: 100));
expect(recipesCubit!.state.recipesList[0].wasLikedByMe, true);
expect(recipesCubit!.state.recipesList[0].likesCount, 11);
await likesStateSubject.close();
});
test('_changeRecipeFavoriteState - обновляет состояние избранного через stream', () async {
final favoriteStateSubject = BehaviorSubject<FavoriteState>();
when(mockAboutRecipeRepository.recipeLikeState).thenAnswer((_) => BehaviorSubject<LikesState>());
when(mockAboutRecipeRepository.recipeFavoriteState).thenAnswer((_) => favoriteStateSubject.stream);
when(mockAboutRecipeRepository.recipeCommentsState).thenAnswer((_) => BehaviorSubject<CommentsState>());
recipesCubit = RecipesCubit(
feedRepository: mockFeedRepository,
recipeRepository: mockRecipeRepository,
aboutRecipeRepository: mockAboutRecipeRepository,
);
const testRecipe = Recipe(
id: 1,
image: 'https://example.com/image.jpg',
state: 'active',
cookingTime: 30,
activeCookingTime: 15,
ingredients: [],
description: 'Test description',
steps: [],
videoUrl: null,
createdAt: null,
updatedAt: null,
title: 'Test Recipe',
type: 'main',
slug: 'test-recipe',
commentsCount: 5,
wasLikedByMe: false,
isFavorite: false,
calories: 300.0,
servings: 4,
likesCount: 10,
viewsCount: 100,
tags: [],
author: Author(authorSlug: 'author', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false, isEntitySubscribedByMe: null, authorPlaceInRating: null),
);
final testTags = [RecipeTag(id: 1, name: 'Tag 1', recipesCount: 10, createdAt: DateTime(2024, 1, 1), updatedAt: DateTime(2024, 1, 2))];
when(mockFeedRepository.getRecipes(tags: anyNamed('tags'), query: anyNamed('query'))).thenAnswer((_) async => [testRecipe]);
when(mockRecipeRepository.getRecipesTags()).thenAnswer((_) async => testTags);
await recipesCubit!.loadRecipesList();
await Future.delayed(const Duration(milliseconds: 200));
// Эмитим новое состояние избранного
favoriteStateSubject.add(const FavoriteState(isFavorite: true, index: 0));
await Future.delayed(const Duration(milliseconds: 100));
expect(recipesCubit!.state.recipesList[0].isFavorite, true);
await favoriteStateSubject.close();
});
test('_changeRecipeCommentsState - обновляет состояние комментариев через stream', () async {
final commentsStateSubject = BehaviorSubject<CommentsState>();
when(mockAboutRecipeRepository.recipeLikeState).thenAnswer((_) => BehaviorSubject<LikesState>());
when(mockAboutRecipeRepository.recipeFavoriteState).thenAnswer((_) => BehaviorSubject<FavoriteState>());
when(mockAboutRecipeRepository.recipeCommentsState).thenAnswer((_) => commentsStateSubject.stream);
recipesCubit = RecipesCubit(
feedRepository: mockFeedRepository,
recipeRepository: mockRecipeRepository,
aboutRecipeRepository: mockAboutRecipeRepository,
);
const testRecipe = Recipe(
id: 1,
image: 'https://example.com/image.jpg',
state: 'active',
cookingTime: 30,
activeCookingTime: 15,
ingredients: [],
description: 'Test description',
steps: [],
videoUrl: null,
createdAt: null,
updatedAt: null,
title: 'Test Recipe',
type: 'main',
slug: 'test-recipe',
commentsCount: 5,
wasLikedByMe: false,
isFavorite: false,
calories: 300.0,
servings: 4,
likesCount: 10,
viewsCount: 100,
tags: [],
author: Author(authorSlug: 'author', authorName: 'Author Name', authorProfileIcon: 'https://example.com/icon.jpg', authorIsMe: false, isEntitySubscribedByMe: null, authorPlaceInRating: null),
);
final testTags = [RecipeTag(id: 1, name: 'Tag 1', recipesCount: 10, createdAt: DateTime(2024, 1, 1), updatedAt: DateTime(2024, 1, 2))];
when(mockFeedRepository.getRecipes(tags: anyNamed('tags'), query: anyNamed('query'))).thenAnswer((_) async => [testRecipe]);
when(mockRecipeRepository.getRecipesTags()).thenAnswer((_) async => testTags);
await recipesCubit!.loadRecipesList();
await Future.delayed(const Duration(milliseconds: 200));
// Эмитим новое состояние комментариев
commentsStateSubject.add(const CommentsState(index: 0, totalComments: 6));
await Future.delayed(const Duration(milliseconds: 100));
expect(recipesCubit!.state.recipesList[0].commentsCount, 6);
await commentsStateSubject.close();
});
test('deleteRecipe - удаляет рецепт', () async {
recipesCubit = RecipesCubit(
feedRepository: mockFeedRepository,
recipeRepository: mockRecipeRepository,
aboutRecipeRepository: mockAboutRecipeRepository,
);
when(mockAboutRecipeRepository.deleteRecipe('test-recipe')).thenAnswer((_) async => Future.value());
final result = await recipesCubit!.deleteRecipe('test-recipe');
expect(result, true);
verify(mockAboutRecipeRepository.deleteRecipe('test-recipe')).called(1);
});
test('deleteRecipe - возвращает false при ошибке', () async {
recipesCubit = RecipesCubit(
feedRepository: mockFeedRepository,
recipeRepository: mockRecipeRepository,
aboutRecipeRepository: mockAboutRecipeRepository,
);
when(mockAboutRecipeRepository.deleteRecipe('test-recipe')).thenThrow(Exception('Ошибка удаления'));
final result = await recipesCubit!.deleteRecipe('test-recipe');
expect(result, false);
});
test('loadNextPage - не загружает если lastPage не инициализирован', () async {
recipesCubit = RecipesCubit(
feedRepository: mockFeedRepository,
recipeRepository: mockRecipeRepository,
aboutRecipeRepository: mockAboutRecipeRepository,
);
// loadNextPage проверяет lastPage, который не инициализирован до loadRecipesList
// Метод выбросит исключение, но мы просто проверяем, что getRecipes не вызывается
try {
await recipesCubit!.loadNextPage();
} catch (e) {
// Ожидаем исключение, так как lastPage не инициализирован
expect(e, isNotNull);
}
verifyNever(mockFeedRepository.getRecipes(page: anyNamed('page'), tags: anyNamed('tags'), query: anyNamed('query')));
});
});
}

View File

@@ -14,6 +14,8 @@ import 'about_plan_cubit_test.mocks.dart';
@GenerateNiceMocks([MockSpec<PlanRepository>()])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('AboutPlanCubit', () {
AboutPlanCubit? aboutPlanCubit;
late MockPlanRepository mockPlanRepository;
@@ -411,5 +413,569 @@ void main() {
expect(result.$1, isNull);
expect(result.$2, 'hasPlan');
});
test('likePlan - лайк плана с index', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.likePlan('test-plan')).thenAnswer((_) async => {});
await aboutPlanCubit!.getPlan('test-plan');
await aboutPlanCubit!.likePlan(index: 5, slug: 'test-plan');
expect(aboutPlanCubit!.state.planModel!.wasLikedByMe, isTrue);
expect(aboutPlanCubit!.state.planModel!.totalLikes, 11);
await Future.delayed(const Duration(milliseconds: 1200));
verify(mockPlanRepository.emitLikesStateToFeed(any)).called(1);
});
test('likePlan - убирает лайк с index', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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: true,
isFavorite: false,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.likePlan('test-plan')).thenAnswer((_) async => {});
await aboutPlanCubit!.getPlan('test-plan');
await aboutPlanCubit!.likePlan(index: 5, slug: 'test-plan');
expect(aboutPlanCubit!.state.planModel!.wasLikedByMe, isFalse);
expect(aboutPlanCubit!.state.planModel!.totalLikes, 9);
await Future.delayed(const Duration(milliseconds: 1200));
verify(mockPlanRepository.emitLikesStateToFeed(any)).called(1);
});
test('likePlan - обрабатывает ошибку', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.likePlan('test-plan')).thenThrow(Exception('Ошибка'));
await aboutPlanCubit!.getPlan('test-plan');
await aboutPlanCubit!.likePlan(index: 5, slug: 'test-plan');
// Проверяем, что состояние изменилось сразу после вызова
expect(aboutPlanCubit!.state.planModel!.wasLikedByMe, isTrue);
expect(aboutPlanCubit!.state.planModel!.totalLikes, 11);
});
test('likePlan - не делает ничего если план не загружен', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
await aboutPlanCubit!.likePlan(index: null, slug: 'test-plan');
expect(aboutPlanCubit!.state.planModel, isNull);
verifyNever(mockPlanRepository.likePlan(any));
});
test('addToFavorite - добавляет план в избранное с index', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.addToFavorite('test-plan')).thenAnswer((_) async => Future<void>.value());
await aboutPlanCubit!.getPlan('test-plan');
await aboutPlanCubit!.addToFavorite(slug: 'test-plan', index: 5);
expect(aboutPlanCubit!.state.planModel!.isFavorite, true);
// Проверяем, что emitFavoriteStateToFeed был вызван сразу после изменения состояния
verify(mockPlanRepository.emitFavoriteStateToFeed(any)).called(1);
});
test('addToFavorite - обрабатывает ошибку', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.addToFavorite('test-plan')).thenThrow(Exception('Ошибка'));
await aboutPlanCubit!.getPlan('test-plan');
await aboutPlanCubit!.addToFavorite(slug: 'test-plan', index: 5);
// Проверяем, что состояние изменилось сразу после вызова
expect(aboutPlanCubit!.state.planModel!.isFavorite, true);
});
test('addToFavorite - не делает ничего если план не загружен', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
await aboutPlanCubit!.addToFavorite(slug: 'test-plan', index: null);
expect(aboutPlanCubit!.state.planModel, isNull);
verifyNever(mockPlanRepository.addToFavorite(any));
});
test('removeFromFavorite - удаляет план из избранного с index', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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: true,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.removeFromFavorite('test-plan')).thenAnswer((_) async => Future<void>.value());
await aboutPlanCubit!.getPlan('test-plan');
await aboutPlanCubit!.removeFromFavorite(slug: 'test-plan', index: 5);
expect(aboutPlanCubit!.state.planModel!.isFavorite, false);
// Проверяем, что emitFavoriteStateToFeed был вызван сразу после изменения состояния
verify(mockPlanRepository.emitFavoriteStateToFeed(any)).called(1);
});
test('removeFromFavorite - обрабатывает ошибку', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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: true,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.removeFromFavorite('test-plan')).thenThrow(Exception('Ошибка'));
await aboutPlanCubit!.getPlan('test-plan');
await aboutPlanCubit!.removeFromFavorite(slug: 'test-plan', index: 5);
// Проверяем, что состояние изменилось сразу после вызова
expect(aboutPlanCubit!.state.planModel!.isFavorite, false);
});
test('removeFromFavorite - не делает ничего если план не загружен', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
await aboutPlanCubit!.removeFromFavorite(slug: 'test-plan', index: null);
expect(aboutPlanCubit!.state.planModel, isNull);
verifyNever(mockPlanRepository.removeFromFavorite(any));
});
test('chosePlan - выбирает план с optionIndex 1', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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,
);
final chosenPlan = ChosenPlanModel(
id: 1,
optionType: 'options2',
startDate: DateTime(2024, 1, 1),
chosenPlanState: ChosenPlanStateEnum.stateStarted,
chatId: 'chat-1',
consultantId: 1,
plan: testPlan,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.chosePlan('test-plan', any)).thenAnswer((_) async => chosenPlan);
await aboutPlanCubit!.getPlan('test-plan');
aboutPlanCubit!.choseOption(1);
final result = await aboutPlanCubit!.chosePlan();
expect(result.$1, isNotNull);
expect(result.$2, isNull);
verify(mockPlanRepository.chosePlan('test-plan', argThat(predicate<Map<String, dynamic>>((map) => map['options_type'] == 'options2')))).called(1);
});
test('chosePlan - выбирает план с optionIndex 2', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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,
);
final chosenPlan = ChosenPlanModel(
id: 1,
optionType: 'options3',
startDate: DateTime(2024, 1, 1),
chosenPlanState: ChosenPlanStateEnum.stateStarted,
chatId: 'chat-1',
consultantId: 1,
plan: testPlan,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.chosePlan('test-plan', any)).thenAnswer((_) async => chosenPlan);
await aboutPlanCubit!.getPlan('test-plan');
aboutPlanCubit!.choseOption(2);
final result = await aboutPlanCubit!.chosePlan();
expect(result.$1, isNotNull);
expect(result.$2, isNull);
verify(mockPlanRepository.chosePlan('test-plan', argThat(predicate<Map<String, dynamic>>((map) => map['options_type'] == 'options3')))).called(1);
});
test('chosePlan - возвращает пустой результат когда slug == null', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
final result = await aboutPlanCubit!.chosePlan();
expect(result.$1, isNull);
expect(result.$2, '');
verifyNever(mockPlanRepository.chosePlan(any, any));
});
test('chosePlan - обрабатывает DioException с другим статусом', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.chosePlan('test-plan', any)).thenThrow(
DioException(
requestOptions: RequestOptions(path: '/api/plans/chose'),
response: Response(statusCode: 500, requestOptions: RequestOptions(path: '/api/plans/chose')),
),
);
await aboutPlanCubit!.getPlan('test-plan');
aboutPlanCubit!.choseOption(0);
final result = await aboutPlanCubit!.chosePlan();
expect(result.$1, isNull);
expect(result.$2, '');
});
test('chosePlan - обрабатывает общее исключение', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async => testPlan);
when(mockPlanRepository.chosePlan('test-plan', any)).thenThrow(Exception('Общая ошибка'));
await aboutPlanCubit!.getPlan('test-plan');
aboutPlanCubit!.choseOption(0);
final result = await aboutPlanCubit!.chosePlan();
expect(result.$1, isNull);
expect(result.$2, '');
});
test('getPlanWithLoading - устанавливает isLoading в true перед загрузкой', () async {
aboutPlanCubit = AboutPlanCubit(planRepository: mockPlanRepository);
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 description',
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,
);
when(mockPlanRepository.getPlan('test-plan')).thenAnswer((_) async {
await Future.delayed(const Duration(milliseconds: 50));
return testPlan;
});
final future = aboutPlanCubit!.getPlanWithLoading('test-plan');
// Проверяем, что isLoading установлен в true сразу после вызова
expect(aboutPlanCubit!.state.isLoading, isTrue);
await future;
expect(aboutPlanCubit!.state.isLoading, isFalse);
});
});
}