Search code examples
javascriptjsoncypresschaiassertion

How to assert that a JSON contains certain keys?


I have successfully converted an excel sheet's content into a JSON, now I am trying to do some validation to it.

I need to assert that the jsonData below contains the following keys: Breakfast, Lunch, Snack, Dinner. It should also be in this specific order.

To test out an assertion first, I tried this:

const jsonData = [{  
  "Breakfast": "Cereal",
  "Lunch": "Chicken",
  "Snack": "Biscuit",
  "Dinner": "Pork",
  "Drinks": "Water"
}]

expect(jsonData).to.be.an('array').that.contains.keys('Breakfast')

And I got this error: AssertionError: expected [ Array(1) ] to contain key 'Breakfast'


Solution

  • Everyone's inputs have been such a big help. This is what I have come up with, let me know if there are ways to improve or if there are better ways to do this.

    // This points to my testdata.json file
    const column = testdata.Meals.column
    
    const key = Object.keys(jsonData[0])
    const value = Object.values(jsonData[0])
    
    const jsonData = [{
      "Breakfast": "Cereal",
      "Lunch": "Chicken",
      "Snack": "Biscuit",
      "Dinner": "Pork",
      "Drinks": "Water"
      "Something": "Else"
    }]
    
    cy.wrap(column).each(($el, index, $list) => {
      expect(jsonData[0]).to.haveOwnProperty(key[index])
    
      // To check the specific order of the key-value pair
      if (index == 0) {
        expect(key[i]).to.eql(column[index])
        expect(value[index]).to.eql(context.mealName)
      } else if (index == 2) {
        expect(key[index]).to.eql(column[index])
        expect(value[index]).to.eql(context.snackName)
      } else if (index == 4) {
        expect(key[index]).to.eql(column[index])
        expect(value[index]).to.eql(context.drinkName)
      }
    })
    

    The testdata.js file:

    {
     "Meals": {
      "column": [
        "Breakfast",
        "Lunch",
        "Snack",
        "Dinner",
        "Drinks"
      ]
     }
    }