javascript - 对条件 Array.sort() 的 Jest 覆盖

标签 javascript sorting if-statement jestjs

我已经非常接近 100% 的测试覆盖率,但我不知道如何覆盖这个条件排序方法。

我尝试按对象的三个属性进行排序:points、goalsDif 然后 goalFor。

  1. 因此,如果点更大,则将索引移动 -1
  2. 如果积分相等但净胜球较大,则将指数移动 -1
  3. 如果points和goalsDif相等但goalsFor更高,则将索引移动-1
  4. 如果没有满足任何条件,则将索引移动 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/

相关文章:

javascript - 如何使用 ul、li 获取树数据数组的 html 嵌套结构

c - 如何获取整数数组的降序(序数)?

java - android 数组列表排序

python - 查找系列中值的百分比变化

java - 程序结束时不考虑 if 语句(编码初学者)

c# - 带有自定义 header 的 Ajax 请求到其他域 WebApi

javascript - jQuery 'this' 元素子元素

javascript - AngularJs 使用 Ajax 验证依赖字段

java - 如何将 !.equals 与字符串一起使用?

if-statement - IF 函数 - 重新格式化组件