如何在jest中检查包含某些键的对象?

时间:2018-05-01 12:35:29

标签: unit-testing typescript jestjs

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

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是一个猫鼬对象。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

看起来你可以通过调用user.toObject()函数将mongoose对象转换为普通对象。一切都按预期工作。

相关问题