如何在javascript测试中比较object2中object1的现有字段?

时间:2018-05-22 15:07:25

标签: javascript node.js testing

我应该比较object1

object2的现有所有字段和值

示例:

object1: {
  user: {
    id: 25,
    name: "Elon"
  }
};

object2: {
  user: {
    id: 25,
    name: "Elon",
    role: "admin"
  },
  rules: [
    "edit"
  ]
}

compareFn(object1, object2); //true

我可以编写这个函数,但我认为它存在于某些测试框架中,但我还没有找到:(

你能帮帮我吗? THX!

1 个答案:

答案 0 :(得分:0)

测试框架Jest将允许您实现此目的。使用他们的toMatchObject断言。您的代码如下:

const object1 = {
  user: {
    id: 25,
    name: "Elon"
  }
};

const object2 = {
  user: {
    id: 25,
    name: "Elon",
    role: "admin"
  },
  rules: [
    "edit"
  ]
}

test('object1 found within object2', () => {
    expect(object2).toMatchObject(object1);
});

文档:https://facebook.github.io/jest/docs/en/expect.html#tomatchobjectobject