Jean-Baptiste THERY
Jean-Baptiste THERY

Reputation: 197

Test object structure with jest

I would need some advice, currently I would like to test that every object in an object collection has the correct structure so I do this:

const allExercises = listAllExercises()

describe("listAllExercises | should return all exercises", () => {
  test("Each exercise should have the right structure", () => {
    const keys = [
      "name",
      "execution",
      "level",
      "is_poly_articular",
      "practice",
      "gender",
      "body_focus",
    ]

    allExercises.forEach((exercise) => {
      expect(Object.keys(exercise).sort()).toEqual(keys.sort())
    })
  })
})

It works great, but I wanted to know if this was the right way to go, do you have a better solution for testing an object's keys with jest?

Upvotes: 2

Views: 2116

Answers (1)

Aziza Kasenova
Aziza Kasenova

Reputation: 1571

You can check it with arrayContaining(array)

const expectedKeys = [
    "name",
    "execution",
    "level",
    "is_poly_articular",
    "practice",
    "gender",
    "body_focus",
];   

expect(array).toEqual(expect.arrayContaining(expectedKeys));

It checks the expected array as a subset of the received value, so it works with a different order, but the same keys present.

Upvotes: 6

Related Questions