expectApiCalledWith function

void expectApiCalledWith(
  1. String endpoint, {
  2. String? method,
  3. dynamic data,
})

Assert that an API endpoint was called with specific request data.

Checks both that the endpoint was called and that the request body matches data via deep equality.

Example:

expectApiCalledWith('/users', method: 'POST', data: {'name': 'John'});

Implementation

void expectApiCalledWith(String endpoint, {String? method, dynamic data}) {
  final calls = NyMockApi.getCallsFor(endpoint).where((c) {
    if (method != null && c.method != method.toUpperCase()) return false;
    return true;
  }).toList();

  expect(calls, isNotEmpty, reason: 'Expected "$endpoint" to have been called');

  if (data != null) {
    final hasMatchingData = calls.any((c) {
      try {
        expect(c.data, equals(data));
        return true;
      } catch (_) {
        return false;
      }
    });

    expect(
      hasMatchingData,
      isTrue,
      reason:
          'Expected "$endpoint" to have been called with data $data '
          'but actual calls had: ${calls.map((c) => c.data).toList()}',
    );
  }
}