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.
- So if points is greater then move the index by -1
- If points are equal but goals difference is higher then move the index by -1
- If points and goalsDif are equal but goalsFor is higher then move index by -1
- 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
},
]
Aucun commentaire:
Enregistrer un commentaire