Reputation: 8655
In Jest I need to test an expected value which can be either null or an object
{
main: {
prop1: 'abc',
prop2: '123',
}
}
but if it is an object, then I don't really care what main
contains, I don't care about prop1
or prop2
. I only need to assert that the object contains a key named main
.
Jest reference mentions objectContaining
, but it would still require that I specify at least one of the props
, thus making my code unnecessarily verbose.
Is there any swift way to achieve an assertion that could be named objectContainingKey
, like:
expect(something).toEqual(expect.objectContainingKey('main'))
Upvotes: 9
Views: 13953
Reputation: 8924
Assuming
const something = {
main: {
prop1: 'abc',
prop2: '123',
}
}
Then you can use objectContaining and any to check that something
is an object containing a key main
which contains an object
expect(something).toEqual(
expect.objectContaining({
main: expect.any(Object),
});
);
Upvotes: 8
Reputation: 2424
The docs have something more suitable and more readable than the accepted answer:
expect(obj.main).toBeDefined();
Upvotes: 9
Reputation: 759
or you can do it in a way that is a little tricky
const something = { main: { prop1: 'abc', prop2: '123' } }
expect(Object.keys(something).toString()).toBe('main')
and
expect(Object.keys(something.main).toString()).toBe('prop1')
expect(Object.keys(something.main).toString()).toBe('prop2')
or
expect(Object.keys(something.main))
.toEqual(expect.arrayContaining(['prop1', 'prop2']))
Upvotes: 6