-1

How to check, with Chai, for a property inside the array of objects. My array of objects is like this:

const myObj = [ {fName: 'abc', lName: 'xyz'}, {fName: 'efg', lName: 'lmn'}, ... ]

I want to check that each object must have the property fName and lName irrespective of their value!

P.S. : I know one library named as chai-things, and with that we can achieve this, however if I only want to use chai then ?

lifeisfoo
  • 15,478
  • 6
  • 74
  • 115
  • This answer will help you https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object . Loop through the elements and check if the property is in the dictionary – Francisco de Castro Apr 08 '21 at 18:35
  • agreed. I can loop through it manually, however, I do not want to do that. Anything available in the Chai framework to achieve this? – Yash Parekh Apr 08 '21 at 18:37
  • You can solve this with chai-things https://www.npmjs.com/package/chai-things . After installation do `foods.should.all.have.property('fName', 'lName')` – Francisco de Castro Apr 09 '21 at 04:04

1 Answers1

0

If you don't want to use a for loop or the chai-things library, you can use the deep equal expectation to compare the entire array in a single assertion:

const expect = require('chai').expect;

const myObj = [ {fName: 'abc', lName: 'xyz'}, {fName: 'efg', lName: 'lmn'} ];

describe('Test Suite', () => {
  it('MyObj Test', function() {
    expect(myObj).to.eql([ {fName: 'abc', lName: 'xyz'}, {fName: 'efg', lName: 'lmn'}]);
  });
});

If you change the second object and run the tests, you'll see a very specific error:

AssertionError: expected [ Array(2) ] to deeply equal [ Array(2) ]
  + expected - actual

       "lName": "xyz"
     }
     {
       "fName": "efg"
  -    "lName": "lmn"
  +    "lName": "lmn2"
     }
   ]

Or you must write all expectations explicitily:

expect(myObj).to.be.an('array');
expect(myObj[0]).to.have.property('fName');
expect(myObj[0]).to.have.property('lName');
expect(myObj[1]).to.have.property('fName');
expect(myObj[1]).to.have.property('lName');
// and so on...
lifeisfoo
  • 15,478
  • 6
  • 74
  • 115