What is the current behavior?
Currently Jest offers .toHaveProperty to check for a specific property inside an object
but I couldn't see an easy way of checking for multiples properties.
I am aware that Jest offers expect.extend() to make possible for us to customize a matcher,
but checking for more than one property seems quite usual to me.
Wouldn't it be interesting to have a .toHaveProperties(args) matcher that receives an array
of strings to check?
A fast and naive prototype of what I am proposing using expect.extend:
`
const extend = {
toHaveProperties(received, args) {
const receivedProperties = Object.getOwnPropertyNames(received);
const pass = !args.some(val => receivedProperties.indexOf(val) === -1);
if (pass) {
return {
message: () => `expected ${received} not to have properties of ${args}`,
pass: true,
};
} else {
return {
message: () => `expected ${received} to have properties of ${args}`,
pass: false,
};
}
},
};
expect.extend(extend)
@WederPachecoSilva seems like a pretty simple and useful feature to implement.. I鈥檒l try to create this PR in the next couple of days..
@WederPachecoSilva
toHaveProperty(expectedKey, ...) enables to pass a 2nd arg expectedValue which is optional.. and passing it will assert for a matching key and value..
This behaviour complicates your original idea of passing an array of keys to expect().toHaveProperties(['key1','key2','keyN']).
I thought about passing a 2nd arg which contains matching values, passing an array of tuples or passing a literal object.
i.e.
expect().toHaveProperties(['key1','key2','keyN'],['1','2','N'])
// or...
expect().toHaveProperties([
['key1', '1'],
['key2', '2'],
['keyN', 'N']
])
// or...
expect().toHaveProperties({
'key1': '1',
'key2': '2',
'keyN' :'N'
})
the latter opens a door to further complications.. (full matching objects vs. partial matching)
If you want equality, you should use toMatchObject for partial or toEqual for full match.
@SimenB @WederPachecoSilva .. maybe changing the function to
expect().toHaveKeys(...keys :string[])
will be a better idea?
Yeah, I think that makes more sense. I'm not sure if it's needed in Jest core, though
@elad-yosifon have you checked out jest-extended? It has support for toContainKeys which is the same API to your example toHaveKeys.
@WederPachecoSilva jest-extended also has APIs for checking entries (key/value pairs) in an object see toContainEntries
I'll say that's good enough, then 馃檪
Most helpful comment
@elad-yosifon have you checked out jest-extended? It has support for
toContainKeyswhich is the same API to your exampletoHaveKeys.@WederPachecoSilva jest-extended also has APIs for checking entries (key/value pairs) in an object see
toContainEntries