Home > OS >  How to assert that a JSON contains certain keys?
How to assert that a JSON contains certain keys?

Time:07-28

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'

CodePudding user response:

I would say to.contain.keys can't be applied to the array, but only the first object within the array.

Try splitting out that first item.

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

expect(jsonData).to.be.an('array')

const firstItem = jsonData[0]
expect(firstItem).to.contain.keys('Breakfast')

Syntax for chai keys assertion

Reading the docs, I'm not sure to.contain.keys is correct syntax either.

Try

expect(firstItem).to.include.any.keys('Breakfast')

Simplest method

You can assert that "Breakfast" exists by comparing it to undefined

First object:

expect(jsonData[0].Breakfast).to.not.eq(undefined)

Every object in the array

jsonData.forEach(item => {
  expect(item.Breakfast).to.not.eq(undefined)
}

CodePudding user response:

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"
  ]
 }
}
  • Related