admin管理员组文章数量:1129050
I have a mapModule
where I import components and export them:
import ComponentName from '../components/ComponentName';
export default {
name: ComponentName,
};
How can I test that mapModule
has the correct exported keys, values and that they are not null or undefined?
I have a mapModule
where I import components and export them:
import ComponentName from '../components/ComponentName';
export default {
name: ComponentName,
};
How can I test that mapModule
has the correct exported keys, values and that they are not null or undefined?
6 Answers
Reset to default 293you can use one of those:
toEqual and toMatchObject are template matchers for objects:
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 :
let Obj = {name: 'component name'};
expect(oneObj).toHaveProperty('name') // true
expect(oneObj).toHaveProperty('name', 'component name') // true
In version 23.3.0 of jest,
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
Keep in mind that .toMatchObject
checks
"that a JavaScript object matches a subset of the properties of an object."
So toMatchObject
can have unintended assertions such as:
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
:
expect({ a: 1, b: 2 }).toStrictEqual({ a: 1 }); // fail
Just adding this tip, thought it gave even better granularity to my own tests, especially when matching against arguments to mocked services:
expect.objectContaining({
url: expect.stringContaining('https://'),
})
Alternatively, you can use regex with expect.stringMatching
which tests the given regex against the value. Pretty neat.
expect.stringContaining expect.stringMatching
For a single key you can check out
expect(Boolean(obj[prop])).toBe(true | false);
For multiple key (where all must be present) you can use,
expect(Boolean(obj[prop1]) && Boolean(obj[prop2])).toBe(true | false);
For multiple key (where any one must be present) you can use
expect(Boolean(obj[prop1]) || Boolean(obj[prop2])).toBe(true | false);
Another way is to:
expect(JSON.stringify(object)).toBe(JSON.stringify(object))
This will ensure the objects are the same.
However using this:
expect(object).toMatchObject(object)
is the best option in most cases.
本文标签: javascriptHow can I test for object keys and values equality using JestStack Overflow
版权声明:本文标题:javascript - How can I test for object keys and values equality using Jest? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736729008a1949888.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论