如何使用 Jest 测试部分对象?

我想测试时间是否被正确解析,我只对检查一些属性而不是整个对象感兴趣。在这种情况下,小时和分钟。

我尝试使用 expect(object).toContain(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)
51651 次浏览

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.

If you want to test for part of an object inside an array of objects, use objectContaining within arrayContaining. Here's an example:

test( 'an object in an array of objects', async () => {
const bookData = [
{
id: 1,
book_id: 98764,
book_title: 'My New International Book',
country_iso_code: 'IN',
release_date: '2022-05-24'
},
{
id: 2,
book_id: 98764,
book_title: 'My New International Book',
country_iso_code: 'GB',
release_date: '2022-05-31'
},
{
id: 3,
book_id: 98764,
book_title: 'My New International Book',
country_iso_code: 'US',
release_date: '2022-06-01'
}
];


expect( bookData ).toEqual(
expect.arrayContaining([
expect.objectContaining(
{
country_iso_code: 'US',
release_date: '2022-06-01'
}
)
])
);
} );

I got this from this Medium article.