Is there an Array equality match function that ignores element position in jest.js?

前端 未结 6 1856
栀梦
栀梦 2021-02-06 20:06

I get that .toEqual() checks equality of all fields for plain objects:

expect(
    {"key1":"pin         


        
6条回答
  •  轮回少年
    2021-02-06 20:52

    As already mentioned expect.arrayContaining checks if the actual array contains the expected array as a subset. To check for equivalence one may

    • either assert that the length of both arrays is the same (but that wouldn't result in a helpful failure message)
    • or assert the reverse: That the expected array contains the actual array:
    // This is TypeScript, but remove the types and you get JavaScript
    const expectArrayEquivalence = (actual: T[], expected: T[]) => {
      expect(actual).toEqual(expect.arrayContaining(expected));
      expect(expected).toEqual(expect.arrayContaining(actual));
    };
    

    This still has the problem that when the test fails in the first assertion one is only made aware of the elements missing from actual and no the extra ones that are not in expected.

提交回复
热议问题