【问题标题】:jest comparing objects . string开玩笑比较对象。细绳
【发布时间】:2020-04-30 05:13:52
【问题描述】:

我收到这个结果是开玩笑的

result1 -> {
        "partyRoleIdentifier": {
          "internalEmployeeIdentifier": {
            "id": "id-modified"
          }
        }
      }

我做了这个比较:

expect(result).toBe('{\"partyRoleIdentifier\": {\"internalEmployeeIdentifier\": {\"id\": \"id-modified\"}}}');

但我得到了这个结果:

 Expected: "{\"partyRoleIdentifier\": {\"internalEmployeeIdentifier\": {\"id\": \"id-modified\"}}}"
    Received: {"partyRoleIdentifier": {"internalEmployeeIdentifier": {"id": "id-modified"}}}

【问题讨论】:

  • 为什么要加斜线?
  • 如果你的结果是一个字符串那么你可以做expect(result).toBe(JSON.stringify({"partyRoleIdentifier": {"internalEmployeeIdentifier": {"id": "id-modified"}}}));
  • 如果结果是 json 那么expect(result).toBe({"partyRoleIdentifier": {"internalEmployeeIdentifier": {"id": "id-modified"}}});

标签: javascript node.js json typescript jestjs


【解决方案1】:

首先,您将字符串与对象进行比较(result 是 JS 对象,而 expected 是字符串)。如果您不想将 JSON 字符串转换为对象,则需要使用 JSON.parse 函数。

let strObj = "{\"foo\":\"bar\"}"
// you can't access object properties from string:
strObj.foo // undefined
let obj = {"foo":"bar"}
obj.foo // "bar"
let parsed = JSON.parse(strObj)
parsed.foo // "bar"

其次,由于在JS中对象是通过引用来比较的,这段代码是比较期望和接收到的引用是否指向同一个对象实例

let a = {foo: "bar"}
let b = {foo: "bar"}
a == b // false

在你的情况下使用expect(result).toMatchObject(expected)。这将检查对象是否与预期的结构和值匹配(执行深度比较)。

jest documentation

使用.toMatchObject 来检查JavaScript 对象是否匹配对象属性的子集。它将匹配接收到的具有不在预期对象中的属性的对象。

因此,您的代码可能会如下所示:

expect(result).toMatchObject({
    partyRoleIdentifier: {
        internalEmployeeIdentifier: {
            id: "id-modified"
        }
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2020-08-20
    • 2018-12-30
    • 2021-07-03
    相关资源
    最近更新 更多