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

它工作得很好,但我想知道这是正确的方式去,你有一个更好的解决方案来测试对象的键与jest?

可以使用arraycontains (array)

进行检查
const expectedKeys = [
"name",
"execution",
"level",
"is_poly_articular",
"practice",
"gender",
"body_focus",
];   
expect(array).toEqual(expect.arrayContaining(expectedKeys));

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

最新更新