Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Could not find mocked route matching request for GET #175

Open
loneObserver1 opened this issue Sep 26, 2024 · 0 comments
Open

Could not find mocked route matching request for GET #175

loneObserver1 opened this issue Sep 26, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@loneObserver1
Copy link

loneObserver1 commented Sep 26, 2024

Description

Error: Assertion failed: "Could not find mocked route matching request for GET https://api.pexels.com/v1/search?query=nothing&per_page=50 { data: null, query parameters: {}, headers: {authorization: YOUR_API_KEY, content-type: application/x-www-form-urlencoded} }"
00:02 +0 -1: ExternalApi.getPexelsImage returns an empty list when search returns no results [E]
DioException [unknown]: null
Error: Assertion failed: "Could not find mocked route matching request for GET https://api.pexels.com/v1/search?query=nothing&per_page=50 { data: null, query parameters: {}, headers: {authorization: YOUR_API_KEY, content-type: application/x-www-form-urlencoded} }"
package:dio/src/dio_mixin.dart 520:7 DioMixin.fetch

Here my code :

class ExternalApi {
  static Future<List<String>> getPexelsImage(String search, {Dio? dio}) async {
    dio ??= Dio();
    List<String> resultImage = [];
    try {
      final result = await dio.get(
        'https://api.pexels.com/v1/search?query=$search&per_page=50',
        options: Options(
          headers: {
            HttpHeaders.authorizationHeader: Keys.pexelsKey
          }, // Vérifiez si la clé est correcte ici
          contentType: 'application/x-www-form-urlencoded',
        ),
      );
      for (final photo in result.data['photos']) {
        resultImage.add(photo['src']['large']);
      }
      debugPrint('SUCCESS');
      debugPrint(result.headers.toString());
      return resultImage;
    } on DioException catch (e) {
      debugPrint('ERREUR ' + e.toString());
      rethrow;
    }
  }
}

Here my test :

void main() {
  late Dio dio;
  late DioAdapter dioAdapter;

  const String baseUrl = 'https://api.pexels.com';
  const String apiKey = 'YOUR_API_KEY'; // Remplacez par votre clé d'API

  setUp(() {
    Keys.pexelsKey = apiKey;

    dio = Dio(BaseOptions(baseUrl: baseUrl));
    dioAdapter = DioAdapter(dio: dio, matcher: const FullHttpRequestMatcher());
    dio.options.headers[HttpHeaders.authorizationHeader] =
        apiKey; // Définir l'en-tête d'autorisation ici
  });

  tearDown(() {
    dioAdapter.close(); // Ferme l'adaptateur après les tests
  });

  group('ExternalApi.getPexelsImage', () {
    /*test('returns a list of images when search returns results', () async {
      const searchQuery = 'nature';
      const route = '/v1/search?query=$searchQuery&per_page=50';

      // Simule une réponse de l'API Pexels avec des données
      dioAdapter.onGet(
        route,
        (server) {
          server.reply(200, {
            "total_results": 1,
            "photos": [
              {
                "src": {
                  "large":
                      "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png?auto=compress&cs=tinysrgb&h=650&w=940"
                }
              }
            ]
          });
        },
        // Ajoutez une vérification des en-têtes pour le mock
        queryParameters: {'query': searchQuery, 'per_page': '50'},
        headers: {HttpHeaders.authorizationHeader: apiKey},
      );

      final result = await ExternalApi.getPexelsImage(searchQuery, dio: dio);

      expect(result, [
        "https://images.pexels.com/photos/3573351/pexels-photo-3573351.png?auto=compress&cs=tinysrgb&h=650&w=940"
      ]);
    });*/

    test('returns an empty list when search returns no results', () async {
      const searchQuery = 'nothing';
      const route = '/v1/search?query=$searchQuery&per_page=50';

      // Simule une réponse de l'API Pexels sans résultats
      dioAdapter.onGet(
        route,
        (server) {
          server.reply(200, {"total_results": 0, "photos": []});
        },
      );

      final result = await ExternalApi.getPexelsImage(searchQuery, dio: dio);

      debugPrint('result $result');

      expect(result, []);
    });

    test('throws a DioException on error', () async {
      const searchQuery = 'errorcase';
      const route = '/v1/search?query=$searchQuery&per_page=50';

      // Simule une erreur de l'API
      dioAdapter.onGet(
        route,
        (server) {
          server.throws(
            500,
            DioException(
              requestOptions: RequestOptions(path: ''),
              response: Response(
                requestOptions: RequestOptions(path: ''),
                statusCode: 500,
              ),
              type: DioExceptionType.badResponse,
            ),
          );
        },
        queryParameters: {'query': searchQuery, 'per_page': '50'},
        headers: {HttpHeaders.authorizationHeader: apiKey},
      );

      // Vérifie que l'erreur est lancée correctement
      expect(
        () async => await ExternalApi.getPexelsImage(searchQuery, dio: dio),
        throwsA(isA<DioException>()),
      );
    });
  });
}


Can someone help me
@loneObserver1 loneObserver1 added the bug Something isn't working label Sep 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant