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

前端 未结 6 1781
栀梦
栀梦 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:51

    If you don't have array of objects, then you can simply use sort() function for sorting before comparison.(mentioned in accepted answer):

    expect(["ping wool", "diorite"].sort()).toEqual(["diorite", "pink wool"].sort());
    

    However, problem arises if you have array of objects in which case sort function won't work. In this case, you need to provide custom sorting function. Example:

    const x = [
    {key: 'forecast', visible: true},
    {key: 'pForecast', visible: false},
    {key: 'effForecast', visible: true},
    {key: 'effRegForecast', visible: true}
    ]
    
    // In my use case, i wanted to sort by key
    const sortByKey = (a, b) => { 
      if(a.key < b.key) return -1; 
      else if(a.key > b.key) return 1; 
      else return 0; 
      }
    
    x.sort(sortByKey)
    console.log(x)

    Hope it helps someone someday.

提交回复
热议问题