【问题标题】:Why does this test still expect my function to throw an error even if I have already done so?为什么即使我已经这样做了,这个测试仍然期望我的函数抛出错误?
【发布时间】:2016-12-31 06:37:44
【问题描述】:

timeseries 是一个格式如下的数组:

[ {"date": "2012-12-21", "price": 1.234}, ... ]

我的代码:

function first(timeseries) {
  if (timeseries.length === 0) {
    return undefined;
  }
  var earliestIndex = 0;
  for (var i = 0; i < timeseries.length; i++) {
    if (timeseries[i].date === null) {
      throw new Error("no date");
    } else {
      if(Date.parse(timeseries[i].date) < Date.parse(timeseries[earliestIndex].date)) {
        earliestIndex = i;
      }
    }
  }
  return timeseries[earliestIndex].price;
}

测试结果:

该问题未指定日期的确切值(未提供)。

为什么会这样?我已经抛出了一个错误。

【问题讨论】:

  • 请在帖子中以文本形式提供代码
  • 那么,如果没有提供日期,值是多少?真的是null...吗?
  • 你能提供测试用例#3的测试数据吗?

标签: javascript arrays exception error-handling throw


【解决方案1】:

涵盖所有情况的一些建议。

  1. 在返回之前测试 timeseries[i].price 是否为空。

  2. 您可能想尝试使用== 而不是===,因为它还会在检查之前进行必要的类型转换。

参考:https://stackoverflow.com/a/359509/4874271

提示:复制代码并在此处格式化而不是发布照片,这样人们会更容易回答。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    相关资源
    最近更新 更多