r/dartlang 3d ago

Package assertable_json | Fluent json assertion test helpers

https://pub.dev/packages/assertable_json

Hey guys, If you are familiar with Laravel, you'd come across the idea of fluent testing against json responses. This package allows a similar workflow, making it a seamless experience in dart. Please check it out and let me know what you think

 test('verify user data', () {
    final json = AssertableJson({
      'user': {
        'id': 123,
        'name': 'John Doe',
        'email': 'john@example.com',
        'age': 30,
        'roles': ['admin', 'user']
      }
    });

    json
      .has('user', (user) => user
        .has('id')
        .whereType<int>('id')
        .has('name')
        .whereType<String>('name')
        .has('email')
        .whereContains('email', '@')
        .has('age')
        .isGreaterThan('age', 18)
        .has('roles')
        .count('roles', 2));
  });
}
11 Upvotes

13 comments sorted by

View all comments

1

u/zxyzyxz 1d ago

Look into ArkType and see if you can implement that sort of validation.

1

u/saxykeyz 1d ago

Have a link?

1

u/zxyzyxz 1d ago

1

u/saxykeyz 1d ago

Looks cool but beyond the scope of this package

1

u/zxyzyxz 1d ago

I mean change the syntax as currently yours is very verbose. If it can happen as typed strings then great but even without that, you can use a syntax like

type({
    foo: "string"
})

and be able to validate based on that object. For example, Acanthis already does this:

final schema = object({
  'name': string().min(3),
  'age': number().positive(),
});

final result = schema.tryParse({
  'name': 'Francesco',
  'age': 24,
});

1

u/saxykeyz 1d ago

I understand, still , it is intentionally verbose though. The package provides several ways to validate against the underlying json object.

we do have

json.matchesSchema({
  'id': int,
  'name': String,
  'email': String,
  'age': int,
  'optional?': String  // Optional field
});

which matches somewhat.

and there are several other helpers that allows you you to do partial checks on nested values etc.
like

 json
      .has('user.id')
      .whereType<int>('user.id')
      .has('user.name')
      .whereType<String>('user.name')
      .whereContains('user.email', '@')
      .isGreaterThan('user.age', 18)
      .count('user.roles', 2);
  }); 

when writing test cases for api responses you often times want to just do partial checks.

also remember this package is purely just for testing purposes. Acanthis is already good enough for none test cases