assertJsonPath method

TestResponse assertJsonPath(
  1. String path,
  2. dynamic expected
)

Asserts that a specific JSON path matches expected. Supports simple dot notation (e.g., 'user.id').

Implementation

TestResponse assertJsonPath(String path, dynamic expected) {
  final decoded = jsonDecode(raw.body);
  final segments = path.split('.');
  var current = decoded;

  for (final segment in segments) {
    if (current is Map && current.containsKey(segment)) {
      current = current[segment];
    } else if (current is List) {
      final index = int.tryParse(segment);
      if (index != null && index >= 0 && index < current.length) {
        current = current[index];
      } else {
        fail('Index "$segment" invalid for List at path "$path"');
      }
    } else {
      fail('Path "$path" not found in JSON response: ${raw.body}');
    }
  }

  expect(current, expected);
  return this;
}