When testing a object with properties with an empty object, my test PASSES:
it('Should not match object with properties with empty object', () => {
const testingObject = { a: 1, b: 2 };
expect(testingObject).toMatchObject({});
});
Now, when comparing with object that has another property that is not part of the testingObject
my test PASSES, which is expected:
it('Should not match object with property that does not exist in the original object', () => {
const testingObject = { a: 1, b: 2 };
expect(testingObject).not.toMatchObject({ c: 3 });
});
This behaviour is strange as i would expect first test to fail because {}
does not have a
and b
properties.
CodePudding user response:
It turns out that this is an expected behaviour per this Jest Github issue.
Also one of the contributors added an explanation:
non-empty received object like {hello: 'hello'} does match empty expected object
empty received object does not match non-empty expected object like {hello: 'hello'}
That is, received value must have all the expected properties, but can have additional properties.
This means that we should expect for this to happen for expected empty object is at least an object same as received object, but cannot have properties that are not part of the received object.
SOLUTION:
(EDIT from comment:)
There is an option for checking a property existence, and also to check value along with that property check.
it('Should not match object with properties with empty object', () => {
const testingObject = { a: 1, b: 2 };
expect(testingObject).toHaveProperty('a', 1);
expect(testingObject).toHaveProperty('b', 2);
});
This solution is a bit explicit and it does not solve the original problem with equality of empty object.