test(tests): add extensive widget tests for MarkdownEditor and CommentsActionsBottomSheet, improving test coverage and functionality validation

This commit is contained in:
mso7nueh
2025-12-11 21:19:41 +03:00
parent d1753e99f8
commit c378c7fc16
44 changed files with 1783 additions and 2 deletions

View File

@@ -1,5 +1,6 @@
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:vk_id/vk_id.dart';
void main() {
group('AuthResultEntity', () {
@@ -100,5 +101,21 @@ void main() {
expect(GenderEnum.female, isNotNull);
expect(GenderEnum.notSet, isNotNull);
});
test('fromVkGender returns correct enum for VkSex.male', () {
expect(GenderEnum.fromVkGender(VkSex.male), GenderEnum.male);
});
test('fromVkGender returns correct enum for VkSex.female', () {
expect(GenderEnum.fromVkGender(VkSex.female), GenderEnum.female);
});
test('fromVkGender returns correct enum for VkSex.notStated', () {
expect(GenderEnum.fromVkGender(VkSex.notStated), GenderEnum.notSet);
});
test('fromVkGender returns null for null VkSex', () {
expect(GenderEnum.fromVkGender(null), null);
});
});
}

View File

@@ -123,6 +123,200 @@ void main() {
// Состояние должно быть error из-за ошибки загрузки профиля
expect(cubit!.state, isA<ProfileAvatarStateError>());
});
test('getMyProfile - обработка ошибки при получении деталей профиля', () async {
cubit = ProfileAvatarCubit(profileRepository: mockRepository);
const testProfile = ProfileModel(
id: 1,
slug: 'test-user',
name: 'Test User',
email: 'test@example.com',
phoneConfirmationState: 'confirmed',
isPublicProfile: true,
isBlockedByMe: false,
isBlockedByAuthor: false,
isBlockedByUser: false,
isEntitySubscribedByMe: false,
profilePhotoUrl: 'https://example.com/icon.jpg',
roles: [],
badges: [],
subscriptions: [],
subscribers: [],
);
when(mockRepository.getMyProfile())
.thenAnswer((_) async => testProfile);
when(mockRepository.getMyProfileDetails())
.thenThrow(Exception('Ошибка загрузки деталей'));
await cubit!.getMyProfile();
await Future.delayed(const Duration(milliseconds: 100));
// Если детали не загрузились, выбрасывается исключение и состояние становится error
expect(cubit!.state, isA<ProfileAvatarStateError>());
});
test('getMyProfile - обработка ошибки при получении профиля', () async {
cubit = ProfileAvatarCubit(profileRepository: mockRepository);
when(mockRepository.getMyProfile())
.thenThrow(Exception('Ошибка загрузки профиля'));
await cubit!.getMyProfile();
// Состояние должно быть error
expect(cubit!.state, isA<ProfileAvatarStateError>());
final errorState = cubit!.state as ProfileAvatarStateError;
expect(errorState.errorMessage, contains('Ошибка загрузки профиля'));
});
test('getMyProfile - успешная загрузка с женским полом', () async {
cubit = ProfileAvatarCubit(profileRepository: mockRepository);
const testProfile = ProfileModel(
id: 1,
slug: 'test-user',
name: 'Test User',
email: 'test@example.com',
phoneConfirmationState: 'confirmed',
isPublicProfile: true,
isBlockedByMe: false,
isBlockedByAuthor: false,
isBlockedByUser: false,
isEntitySubscribedByMe: false,
profilePhotoUrl: 'https://example.com/icon.jpg',
roles: [],
badges: [],
subscriptions: [],
subscribers: [],
);
const testProfileDetails = ProfileDetailsModel(
firstName: 'Test',
lastName: 'User',
birthdate: '1990-01-01',
gender: 'female',
country: 'Russia',
city: 'Moscow',
lang: 'ru',
weight: 60.0,
height: 165,
chestCircumference: 90,
waistCircumference: 70,
hipCircumference: 95,
bloodPressureUp: 110,
bloodPressureDown: 70,
hasHypo: false,
hasHyper: false,
aboutAlergy: 'No allergies',
aboutTakingPils: 'No pills',
aboutSportHobbies: 'Yoga',
favoriteFoods: 'Vegetables',
unfavoriteFoods: 'Meat',
additionalInfo: 'Additional info',
isMoodFillable: true,
isBedtimeFillable: true,
activityCoefficient: 1.2,
);
when(mockRepository.getMyProfile())
.thenAnswer((_) async => testProfile);
when(mockRepository.getMyProfileDetails())
.thenAnswer((_) async => testProfileDetails);
ProfileAvatarState? loadedState;
final subscription = cubit!.stream.listen((state) {
if (state is ProfileAvatarStateLoaded) {
loadedState = state;
}
});
try {
await cubit!.getMyProfile();
await Future.delayed(const Duration(milliseconds: 100));
} catch (e) {
// Игнорируем ошибки плагинов
} finally {
await subscription.cancel();
}
expect(loadedState, isNotNull);
});
test('getMyProfile - успешная загрузка с различными форматами даты рождения', () async {
cubit = ProfileAvatarCubit(profileRepository: mockRepository);
const testProfile = ProfileModel(
id: 1,
slug: 'test-user',
name: 'Test User',
email: 'test@example.com',
phoneConfirmationState: 'confirmed',
isPublicProfile: true,
isBlockedByMe: false,
isBlockedByAuthor: false,
isBlockedByUser: false,
isEntitySubscribedByMe: false,
profilePhotoUrl: 'https://example.com/icon.jpg',
roles: [],
badges: [],
subscriptions: [],
subscribers: [],
);
// Тест с датой рождения в будущем (для проверки расчета возраста)
const testProfileDetails = ProfileDetailsModel(
firstName: 'Test',
lastName: 'User',
birthdate: '2000-06-15',
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: 'No allergies',
aboutTakingPils: 'No pills',
aboutSportHobbies: 'Running',
favoriteFoods: 'Fruits',
unfavoriteFoods: 'Fast food',
additionalInfo: 'Additional info',
isMoodFillable: true,
isBedtimeFillable: true,
activityCoefficient: 1.5,
);
when(mockRepository.getMyProfile())
.thenAnswer((_) async => testProfile);
when(mockRepository.getMyProfileDetails())
.thenAnswer((_) async => testProfileDetails);
ProfileAvatarState? loadedState;
final subscription = cubit!.stream.listen((state) {
if (state is ProfileAvatarStateLoaded) {
loadedState = state;
}
});
try {
await cubit!.getMyProfile();
await Future.delayed(const Duration(milliseconds: 100));
} catch (e) {
// Игнорируем ошибки плагинов
} finally {
await subscription.cancel();
}
expect(loadedState, isNotNull);
});
});
}

View File

@@ -66,3 +66,6 @@ void main() {

View File

@@ -53,3 +53,6 @@ void main() {

View File

@@ -85,3 +85,6 @@ void main() {

View File

@@ -103,3 +103,6 @@ void main() {

View File

@@ -133,3 +133,6 @@ void main() {

View File

@@ -45,3 +45,6 @@ void main() {

View File

@@ -46,3 +46,6 @@ void main() {

View File

@@ -189,6 +189,225 @@ void main() {
verify(mockWsManager.newNotificationsStream).called(1);
});
test('loadMoreNotifications - обработка ошибки при загрузке', () async {
final notifications = [
ChosenPlanStartedToClientNotification(
type: NotificationType.chosenPlanStartedToClientNotification,
planName: 'Plan 1',
planId: 1,
isRead: false,
createdAt: DateTime.now(),
),
];
when(mockNotificationsRepository.getNotifications(page: 1))
.thenAnswer((_) async => {
'notifications': notifications,
'pagination': {'current_page': 1, 'last_page': 2},
});
when(mockNotificationsRepository.getNotifications(page: 2))
.thenThrow(Exception('Ошибка загрузки'));
await cubit.getNotifications();
await cubit.loadMoreNotifications();
final state = cubit.state;
expect(state, isA<NotificationsStateLoaded>());
if (state is NotificationsStateLoaded) {
expect(state.isLoadingMore, false);
}
});
test('loadMoreNotifications - не загружает если уже загружается', () async {
final notifications = [
ChosenPlanStartedToClientNotification(
type: NotificationType.chosenPlanStartedToClientNotification,
planName: 'Plan 1',
planId: 1,
isRead: false,
createdAt: DateTime.now(),
),
];
when(mockNotificationsRepository.getNotifications(page: 1))
.thenAnswer((_) async => {
'notifications': notifications,
'pagination': {'current_page': 1, 'last_page': 2},
});
when(mockNotificationsRepository.getNotifications(page: 2))
.thenAnswer((_) async {
await Future.delayed(const Duration(milliseconds: 50));
return {
'notifications': notifications,
'pagination': {'current_page': 2, 'last_page': 2},
};
});
await cubit.getNotifications();
// Вызываем loadMoreNotifications дважды быстро
final future1 = cubit.loadMoreNotifications();
// Небольшая задержка, чтобы первый вызов успел установить isLoadingMore
await Future.delayed(const Duration(milliseconds: 10));
final future2 = cubit.loadMoreNotifications();
await future1;
await future2;
// Должен быть вызван только один раз, так как второй вызов должен быть заблокирован isLoadingMore
verify(mockNotificationsRepository.getNotifications(page: 2)).called(1);
});
test('markNotificationsAsRead - обработка ошибки', () async {
final notifications = [
ChosenPlanStartedToClientNotification(
type: NotificationType.chosenPlanStartedToClientNotification,
planName: 'Plan 1',
planId: 1,
isRead: false,
createdAt: DateTime.now(),
),
];
when(mockNotificationsRepository.getNotifications(page: 1))
.thenAnswer((_) async => {
'notifications': notifications,
'pagination': {'current_page': 1, 'last_page': 1},
});
when(mockNotificationsRepository.markNotificationsAsRead())
.thenThrow(Exception('Ошибка пометки'));
await cubit.getNotifications();
await cubit.markNotificationsAsRead();
final state = cubit.state;
expect(state, isA<NotificationsStateLoaded>());
if (state is NotificationsStateLoaded) {
expect(state.isLoading, false);
}
});
test('getNotifications - возвращает null от репозитория', () async {
when(mockNotificationsRepository.getNotifications(page: 1))
.thenAnswer((_) async => null);
await cubit.getNotifications();
// Состояние должно остаться empty
expect(cubit.state, isA<NotificationsStateEmpty>());
});
test('loadMoreNotifications - возвращает null от репозитория', () async {
final notifications = [
ChosenPlanStartedToClientNotification(
type: NotificationType.chosenPlanStartedToClientNotification,
planName: 'Plan 1',
planId: 1,
isRead: false,
createdAt: DateTime.now(),
),
];
when(mockNotificationsRepository.getNotifications(page: 1))
.thenAnswer((_) async => {
'notifications': notifications,
'pagination': {'current_page': 1, 'last_page': 2},
});
when(mockNotificationsRepository.getNotifications(page: 2))
.thenAnswer((_) async => null);
await cubit.getNotifications();
await cubit.loadMoreNotifications();
final state = cubit.state;
expect(state, isA<NotificationsStateLoaded>());
if (state is NotificationsStateLoaded) {
expect(state.isLoadingMore, false);
expect(state.notifications.length, 1); // Только первая страница
}
});
test('getNotifications - проверяет hasUnreadNotifications', () async {
final notifications = [
ChosenPlanStartedToClientNotification(
type: NotificationType.chosenPlanStartedToClientNotification,
planName: 'Plan 1',
planId: 1,
isRead: false,
createdAt: DateTime.now(),
),
ChosenPlanStartedToClientNotification(
type: NotificationType.chosenPlanStartedToClientNotification,
planName: 'Plan 2',
planId: 2,
isRead: true,
createdAt: DateTime.now(),
),
];
final result = {
'notifications': notifications,
'pagination': {
'current_page': 1,
'last_page': 1,
},
};
when(mockNotificationsRepository.getNotifications(page: 1))
.thenAnswer((_) async => result);
await cubit.getNotifications();
final state = cubit.state;
expect(state, isA<NotificationsStateLoaded>());
if (state is NotificationsStateLoaded) {
expect(state.hasUnreadNotifications, true); // Есть непрочитанное
}
});
test('getNotifications - hasUnreadNotifications false когда все прочитаны', () async {
final notifications = [
ChosenPlanStartedToClientNotification(
type: NotificationType.chosenPlanStartedToClientNotification,
planName: 'Plan 1',
planId: 1,
isRead: true,
createdAt: DateTime.now(),
),
ChosenPlanStartedToClientNotification(
type: NotificationType.chosenPlanStartedToClientNotification,
planName: 'Plan 2',
planId: 2,
isRead: true,
createdAt: DateTime.now(),
),
];
final result = {
'notifications': notifications,
'pagination': {
'current_page': 1,
'last_page': 1,
},
};
when(mockNotificationsRepository.getNotifications(page: 1))
.thenAnswer((_) async => result);
await cubit.getNotifications();
final state = cubit.state;
expect(state, isA<NotificationsStateLoaded>());
if (state is NotificationsStateLoaded) {
expect(state.hasUnreadNotifications, false); // Все прочитаны
}
});
});
}

View File

@@ -171,3 +171,6 @@ void main() {