refactor(profile): update ProfileRepository to include MockRef for improved testing and enhance error handling in API calls

This commit is contained in:
Nils-Johan Gynther
2026-04-23 18:01:13 +02:00
parent 2256ddb29b
commit 5644101b68
2 changed files with 8 additions and 7 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ class ApiClient {
if (token != null) 'Authorization': 'Bearer $token',
};
Future<dynamic> getJson(String path, {String? token}) async {
Future<Map<String, dynamic>> getJson(String path, {String? token}) async {
final response = await _client.get(
Uri.parse('$baseUrl$path'),
headers: _headers(token: token),
@@ -13,7 +13,8 @@ void main() {
setUp(() {
mockApiClient = MockApiClient();
profileRepository = ProfileRepository(mockApiClient);
final mockRef = MockRef();
profileRepository = ProfileRepository(mockApiClient, mockRef);
});
group('getProfile', () {
@@ -27,7 +28,7 @@ void main() {
verify(mockApiClient.getJson('/api/profile')).called(1);
});
test('should throw ApiException when API call fails', () async {
test('should throw ApiException when API call fails', () async {, type: ApiErrorType.server
when(mockApiClient.getJson('/api/profile')).thenThrow(ApiException(message: 'Failed to fetch profile'));
expect(() => profileRepository.getProfile(), throwsA(isA<ApiException>()));
@@ -39,20 +40,20 @@ void main() {
test('should return updated profile data when API call is successful', () async {
final profileData = {'username': 'newuser', 'email': 'new@example.com'};
final expectedProfile = {'username': 'newuser', 'email': 'new@example.com'};
when(mockApiClient.patchJson('/api/profile', profileData)).thenAnswer((_) async => expectedProfile);
when(mockApiClient.patchJson(any, profileData)).thenAnswer((_) async => expectedProfile);
final result = await profileRepository.updateProfile(profileData);
expect(result, expectedProfile);
verify(mockApiClient.patchJson('/api/profile', profileData)).called(1);
verify(mockApiClient.patchJson(any, profileData)).called(1);
});
test('should throw ApiException when API call fails', () async {
final profileData = {'username': 'newuser', 'email': 'new@example.com'};
when(mockApiClient.patchJson('/api/profile', profileData)).thenThrow(ApiException(message: 'Failed to update profile'));
when(mockApiClient.patchJson(any, profileData)).thenThrow(ApiException(message: 'Failed to update profile', type: ApiErrorType.server));
expect(() => profileRepository.updateProfile(profileData), throwsA(isA<ApiException>()));
verify(mockApiClient.patchJson('/api/profile', profileData)).called(1);
verify(mockApiClient.patchJson(any, profileData)).called(1);
});
});
});