Jest assertion - object containing a key

use*_*686 3 jestjs

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'))

Eka*_*tra 6

或者你可以用一种有点棘手的方式来做

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)


Luc*_*edo 6

该文档有一些更适合比接受的答案更具可读性:

expect(obj.main).toBeDefined();
Run Code Online (Sandbox Code Playgroud)


Mar*_*Fox 6

假设

const something = {
  main: {
    prop1: 'abc',
    prop2: '123',
  }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用objectContainingany来检查该对象是否包含包含对象的somethingmain

expect(something).toEqual(
  expect.objectContaining({
    main: expect.any(Object),
  });
);
Run Code Online (Sandbox Code Playgroud)