繁体   English   中英

如何编写一个函数来通过 2 个测试

[英]How to write a function to pass 2 tests

我正在学习和练习使用 javascript 编写测试:

这是测试用例find.test.js

var findTheNeedle = require("./find-needle");

test("Find the needle", function () {
  var words = ["house", "train", "slide", "needle", "book"];
  var expected = 3;

  var output = findTheNeedle(words, "needle");

  expect(output).toEqual(expected);
});

test("Find the plant", function () {
  var words = ["plant", "shelf", "arrow", "bird"];
  var expected = 0;

  var output = findTheNeedle(words, "plant");

  expect(output).toEqual(expected);
});

这是我的以下函数find.js

function findNeedle(words) {
  for (var i = 0; i < words.length; i++) {
    if (words[i] === "needle") {
      var needle = i;
    }
  }

  return needle;
}
module.exports = findNeedle;

你应该做这个:

var findTheNeedle = require("./find-needle");

test("Find the object", function () {
  var words = ["house", "train", "slide", "needle", "book"];
  var expected = 3;

  var output = findTheNeedle(words, "needle");

  expect(output).toEqual(expected);

  var words = ["plant", "shelf", "arrow", "bird"];
  var expected = 0;

  var output = findTheNeedle(words, "plant");

  expect(output).toEqual(expected);
});

我认为您需要重新制作该功能,如下所示:

function findInArray( arr, word ) {
  let index = -1
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === word) {
       index = i;
    }
  }

  return index;
}
module.exports = findInArray;

如果任何“期望”失败,则所有测试都将失败

看来您的函数将返回单词列表中“单词”的索引。 这意味着,您的函数必须接收 2 个变量作为参数:“word”和“words”。

我认为当前的函数名(和文件名) - findNeedle不“正确”,所以我建议更改它。 findWordIndex怎么样?

函数逻辑很简单,你可以使用Array.indexOf工具来做,或者按照你的方式来做。

module.exports = (words, word) => words.indexOf(word);

或者

module.exports = (words, word) => {
  for (let i = 0; i < words.length; i++) {
    if (words[i] === word) {
      return i; // stop right after you found it
    }
  }
  return -1;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM