用玩笑测试对象结构

Test object structure with jest

我需要一些建议,目前我想测试对象集合中的每个对象是否具有正确的结构,所以我这样做:

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())
    })
  })
})

效果很好,但我想知道这是否是正确的方法,您是否有更好的解决方案来开玩笑地测试对象的键?

你可以用arrayContaining(array)

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

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

它将预期数组检查为接收值的子集,因此它以不同的顺序工作,但存在相同的键。