Zeus
Zeus

Reputation: 216

Mocha and Chai: JSON contains/includes certain text

Using Mocha and Chai, I am trying to check whether JSON array contains a specific text. I tried multiple things suggested on this site but none worked.

  await validatePropertyIncludes(JSON.parse(response.body), 'scriptPrivacy');

  async validatePropertyIncludes(item, propertyValue) {
    expect(item).to.contain(propertyValue);
  }

Error that I getting: AssertionError: expected [ Array(9) ] to include 'scriptPrivacy'

My response from API:

[
    {
        "scriptPrivacy": {
            "settings": "settings=\"foobar\";",
            "id": "foobar-notice-script",
            "src": "https://foobar.com/foobar-privacy-notice-scripts.js",
        }

Upvotes: 0

Views: 1044

Answers (1)

J.F.
J.F.

Reputation: 15187

You can check if the field is undefined.

If field exists in the JSON object, then won't be undefined, otherwise yes.

Using filter() expresion you can get how many documents don't get undefined.

var filter = object.filter(item => item.scriptPrivacy != undefined).length

If attribute exists into JSON file, then, variable filter should be > 0.

var filter = object.filter(item => item.scriptPrivacy != undefined).length
//Comparsion you want: equal(1) , above(0) ...
expect(filter).to.equal(1)

Edit: To use this method from a method where you pass attribute name by parameter you can use item[propertyName] because properties into objects in node can be accessed as an array.

So the code could be:

//Call function
validatePropertyIncludes(object, 'scriptPrivacy')
function validatePropertyIncludes(object, propertyValue){
    var filter = object.filter(item => item[propertyValue] != undefined).length
    //Comparsion you want: equal(1) , above(0) ...
    expect(filter).to.equal(1)
}

Upvotes: 1

Related Questions