Search code examples
javascriptchaiassertionschakram

Match elements of an array from a JSON Array of Objects using Chai


Let's say I have an array

let array_of_string = ['John','Jack','Smith','Ryan'];

How can I assert that these keys are included in JSON array of objects where the JSON is something like this

[ {
    "person_name": "Jake",
    "person_id": '1234',
    "employee_type": "Regular"
}, {
    "person_name": "Adam",
    "person_id": '1245',
    "employee_type": "Contractor"
}, {
    "person_name": "John",
    "person_id": '2342',
    "employee_type": "Regular"
}, {
    "person_name": "Smith",
    "person_id": '3456',
    "employee_type": "Contractor"
}, {
    "person_name": "Ryan",
    "person_id": '0123',
    "employee_type": "Regular"
} ]

I am using Chai to have the assertions. Using include and deep.Equal doesn't seem to work.

The JSON Array is response of an API. So currently I tried this

it('checks if the elements are in API response', () => {
  return response.then(function(resp){
    expect(resp).to.be.an('array').that.includes(array_of_string )
  })
})

Solution

  • I changed "Jack" to "Jake" in the list of names and removed "Adam" from the response data to ensure that every name appeared in the data to prove the function's use below.

    The JS Doc preceding the function describes what it does.

    /*
     * Check if each value exist (at least once) in a list (by its key).
     * @param {object[]} list - List of objects.
     * @param {string[]} vals - List of values to search for.
     * @param {string}   key  - Key for each object to check the value.
     * @return {boolean} Returns wheteher all values exist in the list.
     */
    const fn = (list, vals, key) => vals.every(val => list.some(e => e[key] === val));
    
    var names = [ 'Jake', 'John', 'Smith', 'Ryan' ];
    var responseData = [{
      "person_name": "Jake",
      "person_id": '1234',
      "employee_type": "Regular"
    }, {
      "person_name": "John",
      "person_id": '2342',
      "employee_type": "Regular"
    }, {
      "person_name": "Smith",
      "person_id": '3456',
      "employee_type": "Contractor"
    }, {
      "person_name": "Ryan",
      "person_id": '0123',
      "employee_type": "Regular"
    }];
    
    // names.every(name => responseData.some(p => p['person_name'] === name));
    console.log('All names present?', fn(responseData, names, 'person_name'));
    .as-console-wrapper { top: 0; max-height: 100% !important; }