Reputation: 1141
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.
Any idea how I might test it?
My array, sort and test look like this:
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
},
]
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;
});
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);
}
})
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
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