Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test part of object using Jest?

I would like to test that time is parsed correctly and I am only interested in checking some of the properties and not the entire object. In this case hour and minutes.

I tried using expect(object).toContain(value) but as you can see in the snippet below it fails although the object contains the properties I am interested in and they have the correct value.

● Calendar > CalendarViewConfig › it should parse time  expect(object).toContain(value)  Expected object:   {"display": "12:54", "full": 774, "hour": 12, "hours": 12, "minutes": 54, "string": "12:54"} To contain value:   {"hours": 12, "minutes": 54}    67 |   it('it should parse time', () => {   68 |     ... > 69 |     expect(parseTime('12:54')).toContain({ hours: 12, minutes: 54})   70 |   })    at Object.<anonymous> (src/Components/Views/Calendar/CalendarViewConfig.test.js:69:32) 
like image 612
mancristiana Avatar asked Mar 01 '18 07:03

mancristiana


People also ask

What is a matcher in Jest?

Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect API doc.

What is deep equality in Jest?

toEqual when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity—this is also known as "deep equal". For example, toEqual and toBe behave differently in this test suite, so all the tests pass.


1 Answers

To check if expected object is a subset of the received object you need to use toMatchObject(object) method:

expect(parseTime('12:54')).toMatchObject({ hours: 12, minutes: 54}) 

or expect.objectContaining(object) matcher:

expect(parseTime('12:54')).toEqual(expect.objectContaining({ hours: 12, minutes: 54})) 

they works in slightly different ways, please take a look at What's the difference between '.toMatchObject' and 'objectContaining' for details.

toContain() is designed to check that an item is in an array.

like image 105
thorin87 Avatar answered Oct 08 '22 23:10

thorin87