我已经非常接近 100% 的测试覆盖率,但我不知道如何覆盖这个条件排序方法。
我尝试按对象的三个属性进行排序:points、goalsDif 然后 goalFor。
- 因此,如果点更大,则将索引移动 -1
- 如果积分相等但净胜球较大,则将指数移动 -1
- 如果points和goalsDif相等但goalsFor更高,则将索引移动-1
- 如果没有满足任何条件,则将索引移动 1
知道如何测试它吗?
我的数组、排序和测试如下所示:
数组
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;
});
测试(开 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);
}
})
编辑
排序数组:
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
},
]
最佳答案
您可以使用对称排序,而无需仅检查较大的值。
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);
关于javascript - 对条件 Array.sort() 的 Jest 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57895949/