【问题标题】:Test object structure with jest用 jest 测试对象结构
【发布时间】:2021-10-12 01:04:24
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript typescript jestjs ts-jest


    【解决方案1】:

    您可以通过arrayContaining(array)查看

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

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

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2018-08-09
      • 2021-11-07
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      相关资源
      最近更新 更多