jeudi 31 décembre 2020

How to set up tests for a Dart HTTP server

I'm trying to build a Dart HTTP server and I want to test the API. I'm not able to set up the tests, though.

Here is what I have so far in my_server_test.dart:

import 'dart:io';

import 'package:my_server/my_server.dart';
import 'package:test/test.dart';

void main() {
  HttpServer server;
  setUp(() async {
    final server = await createServer();
    await handleRequests(server);
  });

  tearDown(() async {
    await server.close(force: true);
    server = null;
  });

  test('First try', () async {
    
    final client = HttpClient();
    final request = await client.get(InternetAddress.loopbackIPv4.host, 4040, '/');
    final response = await request.close();
    print(response);
    
  });
}

And here is the server code in my_server.dart:

import 'dart:io';

import 'package:hundetgel_server/routes/handle_get.dart';

Future<HttpServer> createServer() async {
  final address = InternetAddress.loopbackIPv4;
  const port = 4040;
  return await HttpServer.bind(address, port);
}

Future<void> handleRequests(HttpServer server) async {
  await for (HttpRequest request in server) {
    switch (request.method) {
      case 'GET':
        handleGet(request);
        break;
      default:
        handleDefault(request);
    }
  }
}

void handleGet(HttpRequest request) {
  request.response
    ..write('Hello')
    ..close();
}

void handleDefault(HttpRequest request) {
  request.response
    ..statusCode = HttpStatus.methodNotAllowed
    ..write('Unsupported request: ${request.method}.')
    ..close();
}

When I run the test I just get a timeout:

TimeoutException after 0:00:30.000000: Test timed out after 30 seconds. See https://pub.dev/packages/test#timeouts
dart:isolate  _RawReceivePortImpl._handleMessage
NoSuchMethodError: The method 'close' was called on null.
Receiver: null
Tried calling: close(force: true)
dart:core                              Object.noSuchMethod
2
main.<fn>
test/my_server_test.dart:15
===== asynchronous gap ===========================
dart:async                             _completeOnAsyncError
test/my_server_test.dart        main.<fn>
test/my_server_test.dart:1
main.<fn>
test/my_server_test.dart:14
2

✖ First try
Exited (1)

How do I set up the server so I can start testing it?

Aucun commentaire:

Enregistrer un commentaire