5

I'm trying to make an HTTP request from within a flutter widget test, but for some reason, the widget test always times out after 5 sec, whereas it works perfectly fine in a unit test.

import 'package:flutter_test/flutter_test.dart';
import 'dart:io';
import 'dart:convert';

void main() {
  test('http unit-test works', () async {
    var httpClient = new HttpClient();
    var request = await httpClient.getUrl(Uri.parse('https://api.ipify.org/'));
    var response = await request.close();
    var responseBody = await response.transform(UTF8.decoder).join();
    print('BODY: $responseBody');
  });

  testWidgets('http widget-test does not work', (WidgetTester tester) async {
    var httpClient = new HttpClient();
    var request = await httpClient.getUrl(Uri.parse('https://api.ipify.org/'));
    var response = await request.close();
    var responseBody = await response.transform(UTF8.decoder).join();
    print('BODY: $responseBody');
  });
}

Is the flutter test environment eating my HTTP request here? How can I prevent it from doing this?

Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
Slyon
  • 151
  • 1
  • 2
  • 1
    Why would you want to make HTTP requests in a test? Wouldn't you want to mock that instead? – QuirijnGB Jan 19 '18 at 03:51
  • Sure. But the problem is that my app/test times-out while trying to reach the local mock-http-server. – Slyon Jan 23 '18 at 08:09
  • See https://stackoverflow.com/questions/49166234/flutter-widget-tests-with-networkimage – TWL Jan 30 '20 at 00:30
  • @QuirijnGB What if I have separate live and mock environments in my server, and I want to use the mock environment during flutter tests? – Amarghosh Sep 28 '21 at 10:56

1 Answers1

0

If the cause of the issue is timeouts as you've mentioned, I suggest trying a different network during tests. WidgetTester shouldn't cause issues on HTTP Requests in Flutter Unit Tests. I tried the repro provided, but it worked fine on my tests.

demo

For reference, here's the version of Flutter I'm running on: Flutter version 1.26.0-2.0.pre.281

Omatt
  • 8,564
  • 2
  • 42
  • 144