Tuesday, 11 April 2017

assert.deepPartiallyEqual function for asymmetric assertion of two objects

I'm having a hard time finding good names here, but i'll describe what I want:

An assertion function such as nodes assert.deepEqual(obj1, obj2) but instead of recursively comparing obj1 with obj2 it should have a signature like so: deepPartiallyEqual(spec, obj) and just check that spec "fits" in obj or that obj "conforms" with spec if you wish. (Maybe a good comparison is ramdas whereEq but it's shallow)

(The context of the question is unit-testing)

Example (pass):

spec = {user: {name: 'Elin', age: 30}};
obj = {user: {id: 1, name: 'Elin', sex: 'f', age: 30}};
deepPartiallyEqual(spec, obj);
// would pass

Example (fail):

spec = {user: {name: 'Cedric', age: 31}};
obj = {user: {id: 1, name: 'Elin', sex: 'f', age: 30}};
deepPartiallyEqual(spec, obj);

// should result in a failed test and an error output similar to:

AssertionError: ...
  + expected - actual

   {
      "user": {
  -    "name": "Elin"
  +    "name": "Cedric"
  -    "age": 30,
  +    "age": 31,
      }
   }

Does what I'm describing exist in any assertion library for javascript? On other platforms? ...and if so, what is it called?


Motivation:

I'm asserting things on quite big objects but I'm only interested in testing that some of their (potentially nested) properties have the right values. So I only want to assert a subset of the objects keys. If I have to do a deepEquals my test file will be bloated with object literals with 90% of properties that I'm not really interested in testing anyway.

But at the same time, testing every property separately like so:

assert.equals 'Elin', obj.user.name
assert.equals 30, obj.user.age

...is a bit painful because it's quite many props to test.



via Cotten

No comments:

Post a Comment