In Jest I need to test an expected value which can be either null or an object
{
main: {
prop1: 'abc',
prop2: '123',
}
}
Run Code Online (Sandbox Code Playgroud)
but if it is an object, then I don't really care what main contains, I don't care about prop1 or prop2. I only need to assert that the object contains a key named main.
Jest reference mentions objectContaining, but it would still require that I specify at least one of the props, thus making my code unnecessarily verbose.
Is there any swift way to achieve an assertion that could be named objectContainingKey, like:
expect(something).toEqual(expect.objectContainingKey('main'))
或者你可以用一种有点棘手的方式来做
const something = { main: { prop1: 'abc', prop2: '123' } }
expect(Object.keys(something).toString()).toBe('main')
Run Code Online (Sandbox Code Playgroud)
和
expect(Object.keys(something.main).toString()).toBe('prop1')
expect(Object.keys(something.main).toString()).toBe('prop2')
Run Code Online (Sandbox Code Playgroud)
或者
expect(Object.keys(something.main))
.toEqual(expect.arrayContaining(['prop1', 'prop2']))
Run Code Online (Sandbox Code Playgroud)
假设
const something = {
main: {
prop1: 'abc',
prop2: '123',
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以使用objectContaining和any来检查该对象是否包含包含对象的something键main
expect(something).toEqual(
expect.objectContaining({
main: expect.any(Object),
});
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4364 次 |
| 最近记录: |