How can I check that two objects have the same set of property names?

后端 未结 7 1282
傲寒
傲寒 2020-11-28 06:04

I am using node, mocha, and chai for my application. I want to test that my returned results data property is the same \"type of object\" as one of my model objects (Very si

相关标签:
7条回答
  • 2020-11-28 06:33

    You can serialize simple data to check for equality:

    data1 = {firstName: 'John', lastName: 'Smith'};
    data2 = {firstName: 'Jane', lastName: 'Smith'};
    JSON.stringify(data1) === JSON.stringify(data2)
    

    This will give you something like

    '{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'
    

    As a function...

    function compare(a, b) {
      return JSON.stringify(a) === JSON.stringify(b);
    }
    compare(data1, data2);
    

    EDIT

    If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section

    EDIT 2

    If you just want to check keys...

    function compareKeys(a, b) {
      var aKeys = Object.keys(a).sort();
      var bKeys = Object.keys(b).sort();
      return JSON.stringify(aKeys) === JSON.stringify(bKeys);
    }
    

    should do it.

    0 讨论(0)
提交回复
热议问题