const obj = {a:1, b:2};
test('object "obj" has key "a"', () => {
expect(obj).toHaveProperty('a'); // pass
expect(obj).not.toHaveProperty('b'); // doesn't pass
}
const houseForSale = {
bath: true,
bedrooms: 4,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
area: 20,
wallColor: 'white',
},
};
const desiredHouse = {
bath: true,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
wallColor: expect.stringMatching(/white|yellow/),
// can use regexp for expect structure of string
},
};
test('the house has my desired features', () => {
expect(houseForSale).toMatchObject(desiredHouse); // pass
});
another Test(also can apply to array)
describe('toMatchObject applied to arrays', () => {
test('the number of elements must match exactly', () => {
expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
});
test('.toMatchObject is called for each elements, so extra object properties are okay', () => {
expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
{foo: 'bar'},
{baz: 1},
]);
});
});