Eli Nathan
Eli Nathan

Reputation: 1141

Jest coverage on conditional Array.sort()

I'm so close to 100% test coverage but I can't figure out how to cover this conditional sort method.

I'm trying to sort by three properties of an object: points, goalsDif then goalsFor.

  1. So if points is greater then move the index by -1
  2. If points are equal but goals difference is higher then move the index by -1
  3. If points and goalsDif are equal but goalsFor is higher then move index by -1
  4. If none of the conditions are met then move index by 1

Any idea how I might test it?

My array, sort and test look like this:

Array

const arr = [
  {
    key: "Leicester City games",
    points: 44,
    goalsDif: -15,
    goalsFor: 48
  },
  {
    key: "Stoke City games",
    points: 44,
    goalsDif: -15,
    goalsFor: 41
  },
  {
    key: "Chelsea games",
    points: 93,
    goalsDif: 52,
    goalsFor: 85
  },
]

Sort

arr.sort((a, b) => {
  // Sort by points
  if (a.points > b.points) return -1;
  
  // If points are equal... Sort by goals difference
  else if (a.point) === b.points && a.goalsDif > b.goalsDif) return -1;
  
  /*
    If points and GD are equal... Sort by goals for
    THE LINE BELOW IS WHERE THE TEST COVERAGE SHOWS IS LACKING
  */
  else if ( a.points === b.points && a.goalsDif === b.goalsDif && a.goalsFor > b.goalsFor) return -1;
  
  // If none of the above conditions are met return 1
  return 1;
});

Test (Jest)

it('Finally sort based on goals for', () => {
  // Isoloate the "Leicester City games" and "Stoke City games" object
  const leicesterObj = sanitizedDummyData.filter(item => item.key === "Leicester City games")[0];
  const stokeObj = sanitizedDummyData.filter(item => item.key === "Stoke City games")[0];
  if (leicesterObj.points() === stokeObj.points()
    && leicesterObj.goalsDif()
    && leicesterObj.goalsFor() > stokeObj.goalsFor()) {
    // Expect Leicester to be higher than Stoke in the rankings because of GF
    expect(sanitizedDummyData.indexOf(leicesterObj)).toEqual(sanitizedDummyData.indexOf(stokeObj) - 1);
  }
})

Edit

Sorted array:

const arr = [
  {
    key: "Chelsea games",
    points: 93,
    goalsDif: 52,
    goalsFor: 85
  },
  {
    key: "Leicester City games",
    points: 44,
    goalsDif: -15,
    goalsFor: 48
  },
  {
    key: "Stoke City games",
    points: 44,
    goalsDif: -15,
    goalsFor: 41
  },
  
]

Upvotes: 2

Views: 3175

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

You may use a symmetrical sorting, without checking of only greater values.

const array = [{ key: "Leicester City games", points: 44, goalsDif: -15, goalsFor: 48 }, { key: "Leicester City games", points: 44, goalsDif: -15, goalsFor: 41 }, { key: "Chelsea games", points: 93, goalsDif: 52, goalsFor: 85 }];

array.sort((a, b) => b.points- a.points || b.goalsDif > a.goalsDif || b.goalsFor - a.goalsFor);

console.log(array);

Upvotes: 2

Related Questions