request method

Future<TestResponse> request(
  1. String method,
  2. String path, {
  3. Object? body,
  4. Map<String, String>? headers,
})

Sends a request with any HTTP method.

Implementation

Future<TestResponse> request(
  String method,
  String path, {
  Object? body,
  Map<String, String>? headers,
}) async {
  final uri = Uri.parse('http://localhost:$_port$path');

  final req = await _client.openUrl(method, uri);

  // Disable automatic redirect following so tests can inspect redirect responses
  req.followRedirects = false;

  // Set headers
  headers?.forEach((key, value) {
    req.headers.set(key, value);
  });

  // Write body
  if (body != null) {
    String bodyString;
    if (body is String) {
      bodyString = body;
    } else if (body is Map || body is List) {
      bodyString = jsonEncode(body);
      req.headers.set('content-type', 'application/json');
    } else {
      bodyString = body.toString();
    }
    req.write(bodyString);
  }

  final res = await req.close();
  return TestResponse(res);
}