Dart shelf server returns 503 when testing

114 Views Asked by At

I'm trying to write tests for my shelf server. And it returns 503 when I make a request in my unit tests, even though the server is started in my test setup. I also tested the route I make a call to in my unit test, in my browser, in the duration that unit test runs. And it works. But in my unit test, I get 503.

Is there any way I can test my shelf server? Any alternative solutions will be appreaciated.

void main() {
  late WebServer server;
  setUp(() async {
    server = WebServer();
    await server.run();
  });

  tearDown(() async {
    await server.stop(force: true);
  });

  test('calling /games return hardcoded text', () async {
    final uri = 'http://localhost:8081/games/1';
    print(Uri.parse(uri));
    final response = await http.get(Uri.parse(uri));
    expect(response.statusCode, HttpStatus.ok);
    expect(response.body, 'creating a new game');
  });
}

And here is the code for my server

class WebServer {
  late HttpServer _httpServer;

  Future<HttpServer> run() async {
    final shelfRouter = setupRoutes();
    _httpServer = await io.serve(shelfRouter, 'localhost', 8081);
    return _httpServer;
  }

  Future<void> stop({bool force = true}) => _httpServer.close(force: force);
}

here is the error I get

Expected: <200>
  Actual: <503>

package:matcher                 expect
test/web_server_test.dart 22:5  main.<fn>
0

There are 0 best solutions below