[英]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.我想测试是否正确解析了时间,我只对检查一些属性而不是整个 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.我尝试使用
expect(object).toContain(value)
但正如您在下面的片段中看到的那样,它失败了,尽管 object 包含我感兴趣的属性并且它们具有正确的值。
● 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)
To check if expected object is a subset of the received object you need to use toMatchObject(object)
method: 要检查预期对象是否是接收对象的子集,您需要使用
toMatchObject(object)
方法:
expect(parseTime('12:54')).toMatchObject({ hours: 12, minutes: 54})
or expect.objectContaining(object)
matcher: 或
expect.objectContaining(object)
匹配器:
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. 它们的工作方式略有不同,请查看“.toMatchObject”和“objectContaining”之间的区别 。
toContain()
is designed to check that an item is in an array. toContain()
用于检查项目是否在数组中。
If you want to test for part of an object inside an array of objects , use objectContaining
within arrayContaining
.如果要在对象数组中测试 object 的一部分,请在
arrayContaining
objectContaining
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 .我从这篇 Medium 文章中得到了这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.