【问题标题】:What is causing this AssertionError failure for my unit test on IndexOf arrays是什么导致我对 IndexOf 数组的单元测试出现此 AssertionError 失败
【发布时间】:2019-06-28 01:24:05
【问题描述】:

我正在做一个编码挑战。有一段代码与测试一起编写以测试代码。我对编码很陌生,不知道从哪里开始。

我得到的错误是,“你应该能够确定数组中项目的位置”‣

AssertionError: expected undefined to deeply equal 2

我尝试声明变量并编写循环,但我被告知这些不是解决此问题的方法。我的目标是让测试通过。

这是编写的代码部分:

exports = typeof window === 'undefined' ? global : window;

exports.arraysAnswers = {
  indexOf: function(arr, item) {

  },

这是测试文件夹中的代码:

if ( typeof window === 'undefined' ) {
  require('../../app/arrays');
  var expect = require('chai').expect;
}

describe('arrays', function() {
  var a;

  beforeEach(function() {
    a = [ 1, 2, 3, 4 ];
  });

  it('you should be able to determine the location of an item in an array', function() {
    expect(arraysAnswers.indexOf(a, 3)).to.eql(2);
    expect(arraysAnswers.indexOf(a, 5)).to.eql(-1);
  });

我希望测试通过,但不知道应该从哪里开始。任何帮助表示赞赏。

【问题讨论】:

    标签: javascript arrays object chai


    【解决方案1】:

    您需要从您的 indexOf 函数中返回一些内容:

    indexOf: function(arr, item) {
      let index = -1;
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === item) {
          index = i;
          break;
        }
      }
      return index;
    }
    

    与 JavaScript 中的原生 indexOf 函数一样,如果未找到该项目,它将返回 -1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 2018-03-31
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      相关资源
      最近更新 更多