dart_frog_test 0.1.0 icon indicating copy to clipboard operation
dart_frog_test: ^0.1.0 copied to clipboard

A testing library which makes it easy to test Dart frog services.

Dart Frog Test #

style: very good analysis Powered by Mason License: MIT

A testing library that makes it easy to test Dart Frog services. It offers helpers to mock requests as well as custom matchers in order to write readable expectations.

[!NOTE] This package is still experimental and although it is ready to be used, some/or all of its API might change (with deprecations) in future versions.

Installation 💻 #

❗ In order to start using Dart Frog Test you must have the Dart SDK installed on your machine.

Add dart_frog_test to your pubspec.yaml:

dependencies:
  dart_frog_test:

Install it:

dart pub get

TestRequestContext #

This class makes it simple to mock a RequestContext for a Dart Frog request handler. To use it, simply import it and use its constructor and methods to create the mocker context.

A simple example:

// Mocking a get request, which is the default
import '../../../routes/users/[id].dart' as route;

test('returns ok', () {
  final context = TestRequestContext(
    path: '/users/1',
  );

  final response = route.onRequest(context);
  expect(response.statusCode, equals(200));
});

If the route handler function reads a dependency injected via context, that can also be mocked:

// Mocking a get request, which is the default
import '../../../routes/users/index.dart' as route;

test('returns ok', () {
  final context = TestRequestContext(
    path: '/users',
  );

  final userRepository = /* Create Mock */;

  context.provide<UserRepository>(userRepository);

  final response = route.onRequest(context);
  expect(response.statusCode, equals(200));
});

Check the TestRequestContext constructor for all the available context attributes that can be mocked.

Matchers #

This package also provide test matchers that can be used to do expectation or assertions on top of Dart Frog's Responses:

expectJsonBody(response, {'name': 'Hank'});
expectBody(response, 'Hank');

expect(response, isOk);
expect(response, isBadRequest);
expect(response, isCreated);
expect(response, isNotFound);
expect(response, isUnauthorized);
expect(response, isForbidden);
expect(response, isInternalServerError);
expect(response, hasStatus(301));

await expectNotAllowedMethods(
  route.onRequest,
  contextBuilder: (method) => TestRequestContext(
    path: '/dice',
    method: method,
  ),
  allowedMethods: [HttpMethod.post],
);