Jest: how to test for object keys and values?
In version 23.3.0 of jest,
expect(string).toMatch(string)
expects a string.
Use:
const expected = { name:'component name' }const actual = { name: 'component name', type: 'form' }expect(actual).toMatchObject(expected)
result is passing test
you can use one of those:
toEqual and toMatchObject are template matchers for objects:
let Obj = {name: 'component name', id: 2};expect(oneObj).toEqual({name: 'component name'}) // false, should be exactly equal all Obj keys and values expect(oneObj).toMatchObject({name: 'component name'}) // true
or easly use toHaveProperty :
let Obj = {name: 'component name'};expect(oneObj).toHaveProperty('name') // trueexpect(oneObj).toHaveProperty('name', 'component name') // true
Keep in mind that .toMatchObject
checks
"that a JavaScript object matches a subset of the properties of an object."
So toMatchObject
can have unintended assertions such as:
expect({ a: 1, b: 2 }).toMatchObject({ a: 1 }); // pass
If you do want to match an object exactly, you should use .toStrictEqual
, available since jest 23
:
expect({ a: 1, b: 2 }).toStrictEqual({ a: 1 }); // fail