【问题标题】:Jest/expect "toEquals" failing with undefined properties开玩笑/期望“toEquals”失败,属性未定义
【发布时间】:2019-01-18 16:18:12
【问题描述】:

我正在使用expect(item).toEqual(otherItem)。根据我读过的所有内容,expect({ a: "a", b: undefined }).toEqual({ a: "a" }) 应该可以通过。否则我应该使用toStrictEqualE.g. here, in "basic matches".

但是,我的输出失败了:

     Array [
       Object {
   +     "alertId": undefined,
         "attributes": Array [],
         "destination": "_b",
         "kind": "kind",
         "linkable": "Unlinkable",
         "source": "_a",
   +     "validFrom": undefined,
   +     "validTo": undefined,
       },
   -   Object {
   -     "attributes": Array [],
   -     "destination": "_c",
   -     "kind": "kind",
   -     "linkable": "Unlinkable",
   -     "source": "_a",
   -   },
     ]

知道为什么吗?

【问题讨论】:

  • 如果预期的对象没有与对象相同的属性,即使值未定义,测试也会失败。解决方案是修复您的函数以删除未定义的值或期望具有未定义值的属性在对象中。
  • expect([{ a: "a", b: undefined }]).toEqual([{ a: "a" }]); 怎么会通过呢?我还在大约 10 次测试中测试了这个函数,尽管它们都具有 undefined 值,但它通过了每一个测试。事实上,即使在同一个expect 中,它也会传递一个 值,而使另一个失败。他们都有undefined
  • 啊!我是个白痴。问题实际上不是undefined,整个对象都丢失了。 Jest 正在按预期工作。
  • 嗯,我也学到了一些新东西。不知道toEqual 会与对象松散匹配。
  • 是的,他们添加了toStrictEqual进行严格检查!

标签: javascript jestjs


【解决方案1】:

啊。我是个白痴。开玩笑没有错,测试正确地失败了。我看错了 Jest 的输出。

这是说整个对象:

-   Object {
-     "attributes": Array [],
-     "destination": "_c",
-     "kind": "kind",
-     "linkable": "Unlinkable",
-     "source": "_a",

数组中缺少。尽管它也将undefined 报告为差异,但这并不是导致toEqual 失败的原因。注意destination 是不同的。测试应该返回两个对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2020-11-19
    • 2018-06-17
    相关资源
    最近更新 更多