I have a function:
const sort = (pets,attribute) => _(pets) .filter(pets=> _.get(pets, attribute) !== null) .groupBy(attribute) .value()
Some data:
const pets= [{ id: 1, name: 'snowy', }, { id: 2, name: 'quacky', }, { id: 3, name: 'snowy', age: 5, }, { id: null, name: null, age: null } ] const attribute = 'name'
I am currently trying to write some Jest unit tests for this, that tests if the function returns the correct resultant object after being sorted based off an attribute.
The result of:
sort(pets,attribute)
is something like this:
{ snowy: [ { id: 1, name: 'snowy' }, { id: 3, name: 'snowy', age: 5} ], quacky: [ { id: 2, name: 'quacky' } ] }
Is there a way I can do a expect
to match the two objects snowy
and quacky
here?
The thing I want to test for is that the objects are being correctly grouped by the key.
I’ve tried using something like
const res = sort(users,key) expect(res).toEqual( expect.arrayContaining([ expect.objectContaining({'snowy' : [ { id: 1, name: 'snowy' }, { id: 3, name: 'snowy', age: 5 } ]}, expect.objectContaining({'quacky' : [ { id: 2, name: 'quacky' } ]})) ]) )
which doesn’t seem to work, the received output seems to output:
Expected: ArrayContaining [ObjectContaining {"snowy": [{"id": 1, "name": "snowy"}, {"age": 5, "id": 3, "name": "snowy"}]}] Received: [Function anonymous]
I am unsure what the best method to test this kind of function is either so advice on that would be appreciated.
Advertisement
Answer
If this is what your arrangeBy()
returns:
{ snowy: [ { id: 1, name: 'snowy' }, { id: 3, name: 'snowy', age: 5} ], quacky: [ { id: 2, name: 'quacky' } ] }
Then you can just do:
const expected = { snowy: [ { id: 1, name: 'snowy' }, { id: 3, name: 'snowy', age: 5} ], quacky: [ { id: 2, name: 'quacky' } ] } const res = arrangeBy(users,key) expect(res).toEqual(expected)
But looking at your Error message I guess you have something else mixed up. In the beginning you listed the implementation of a sort
function which seems to not be used in the test. Where is arrangeBy
coming from now.
Please provide more code examples.