jestjs - Jest 断言 - 包含 key 的对象

标签 jestjs

在 Jest 中,我需要测试一个可以为 null 或对象的预期值

{
  main: {
    prop1: 'abc',
    prop2: '123',
  }
}

但如果它是一个对象,那么我真的不在乎 main 包含什么,我不在乎 prop1prop2 。我只需要断言该对象包含一个名为 main 的键。

Jest reference 提到了 objectContaining ,但它仍然需要我指定至少一个 props ,从而使我的代码不必要地冗长。

是否有任何快速的方法来实现可以命名为 objectContainingKey 的断言,例如:
expect(something).toEqual(expect.objectContainingKey('main'))

最佳答案

假设

const something = {
  main: {
    prop1: 'abc',
    prop2: '123',
  }
}
然后你可以使用 objectContainingany 来检查 something 是一个包含键 main 的对象,该键包含一个对象
expect(something).toEqual(
  expect.objectContaining({
    main: expect.any(Object),
  });
);

关于jestjs - Jest 断言 - 包含 key 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51323504/

相关文章:

javascript - Windows 10,运行 jest 时找不到现有的 binding.node 文件

jestjs - Jest + enzyme 测试 : how to ensure a certain function is passed as prop to a component

reactjs - Jest-dom 给出错误 "TypeError: expect(...).toHaveStyle is not a function"

node.js - NodeJS:发现错误:听 EADDRINUSE:::3000?

javascript - 无法让 Jest 模拟正常工作

reactjs - 语法错误: Unexpected token import with Jest + react-native-animated-ellipsis

typescript - 使用动态导入时 Jest 与自定义错误类型不匹配

javascript - 使用 Jest 测试 React 组件

typescript - 让 Jest 使用 ts-jest 和 webpack 识别和解析模块别名需要什么?

javascript - 将 testRunner 设置为 jest-circus 访问 jasmine 会导致 : ReferenceError: jasmine is not defined