首页 > 解决方案 > 如何在玩笑中检查包含某些键的对象?

问题描述

我很困惑。我刚刚开始开玩笑地编写测试,但我无法弄清楚发生了什么。这是我的输出:

Expected value to equal:
  ObjectContaining {"field": "f1", "module": "m1", "rights": {"read": true}}
Received:
  {"_id": "5ae85cd0bc5ad3569bf66df8", "field": "f1", "module": "m1", "rights": {"read": true}}

Difference:

- Expected
+ Received

@@ -1,6 +1,7 @@
- ObjectContaining {
+ Object {
+   "_id": "5ae85cd0bc5ad3569bf66df8",
    "field": "f1",
    "module": "m1",
    "rights": Object {
      "read": true,
    },
  183 |         ]),
  184 |       );
> 185 |       expect(user.acl[0]).toEqual(
  186 |           expect.objectContaining({ module: 'm1', field: 'f1', rights: {read: true}}),
  187 |       );
  188 |     });

我认为它失败是因为它user是一个猫鼬对象。

标签: unit-testingtypescriptjestjs

解决方案


在比较之前,您应该_id从对象中删除。

或者,您应该使用toMatchSnapshot()(但仍需要删除每次运行时会更改的任何键。


推荐阅读