Javascript Jest:如何测试对象键和属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47754777/
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
Jest: How to test for object keys and properties
提问by fasenberg
I have a mapModulewhere I import components and export them:
我有一个mapModule导入组件并导出它们的地方:
import ComponentName from '../components/ComponentName';
export default {
name: ComponentName,
};
How can I test it that mapModulehas the correct exported keys, values and that they are not null or undefined?
我如何测试它是否mapModule具有正确的导出键、值并且它们不为空或未定义?
回答by user3605834
In version 23.3.0 of jest,
在 jest 23.3.0 版本中,
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
结果通过测试
回答by toufek khoury
you can use one of those:
您可以使用其中之一:
toEqual and toMatchObject are template matchers for objects:
toEqual 和 toMatchObject 是对象的模板匹配器:
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 :
或轻松使用 toHaveProperty :
let Obj = {name: 'component name'};
expect(oneObj).toHaveProperty('name') // true
expect(oneObj).toHaveProperty('name', 'component name') // true
回答by rtorres
Keep in mind that .toMatchObjectchecks "that a JavaScript object matches a subset of the properties of an object." So it can have unintended assertions as such:
请记住,.toMatchObject检查“JavaScript 对象是否匹配对象属性的子集”。因此,它可能会有意外的断言,例如:
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:
如果您确实想完全匹配对象,则应使用.toStrictEqual, 可用,因为jest 23:
expect({ a: 1, b: 2 }).toStrictEqual({ a: 1 }); // fail

![Javascript 对象作为 React 子对象无效(找到:[object Promise])](/res/img/loading.gif)