Issue with Mocktail and Dart Frog

112 views Asked by At

I'm new to testing with anything other than Postman and having a problem with tests on my Dart Frog API. Tests on basic endpoints that return a static value work but this one fails with the error "type 'Null' is not a subtype of type 'Request'":

class _MockRequestContext extends Mock implements RequestContext {}

void main() {
  group('GET /api/node_status', () {
    test("responds with a 403 if verb isn't GET", () async {
      const method = 'POST';
      final context = _MockRequestContext();
      when(() => context.read<String>()).thenReturn(method);
      final response = await route.onRequest(context);
      expect(response.statusCode, equals(HttpStatus.forbidden));
    });
    test('responds with a 200 and {"status":"open"}.', () async {
      const method = 'GET';
      final context = _MockRequestContext();
      when(() => context.request.method.value).thenReturn(method);
      final response = await route.onRequest(context);
      expect(response.statusCode, equals(HttpStatus.ok));
      expect(
        response.body(),
        completion(equals('{"status":"open"}')),
      );
    });
  });
}

And my endpoint code is:

Future<Response> onRequest(RequestContext context) async {
  // Reject any method other than GET requests
  if (context.request.method.value != 'GET') {
    return Response(statusCode: 403);
  }
  // Return the node status set in main.dart from config.yaml
  final nodeStatus = <String, dynamic>{'status': globals.nodeStatus};
  return Response(body: jsonEncode(nodeStatus));
}

I've tried setting the value of nodeStatus to a static value with no luck. I'm sure it's something pretty simple, but I can't find much documentation on using Mocktail with Dart Frog aside from some basic examples on the Dart Frog site that I based my tests on.

Edit

It was suggested to mock up the request first and I did so:

class _MockRequestContext extends Mock implements RequestContext {}

class _MockRequestObject extends Mock implements Request {}

void main() {
  group('node_status', () {
    test('responds with a 403 if method is not GET".', () async {
      final context = _MockRequestContext();
      final mockRequest = _MockRequestObject();
      when(() => context.request).thenReturn(mockRequest);
      when(() => mockRequest.method.value).thenReturn('POST');
      final response = await route.onRequest(context);
      expect(response.statusCode, equals(HttpStatus.forbidden));
    });
  });
}

Now my error is:

type 'String' is not a subtype of type 'HttpMethod' test/routes/api/node_status_test.dart 11:7 _MockRequestObject.method routes/api/node_status.dart 8:23 onRequest test/routes/api/node_status_test.dart 20:36 main.<fn>.<fn>

0

There are 0 answers