javascript 如何使用 Jest 测试对象的一部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49044994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I test part of object using Jest?
提问by mancristiana
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.
我尝试使用,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)
回答by thorin87
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()旨在检查项目是否在数组中。

