【问题标题】:How to write a function to pass 2 tests如何编写一个函数来通过 2 个测试
【发布时间】:2021-09-25 17:15:49
【问题描述】:

我正在学习和练习用 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;

【问题讨论】:

  • function findNeedle(words, word) { return words.indexOf(word); }
  • @hoangdv - 如果您将其移至答案,OP 可能更有可能看到它:) 做得很好。

标签: javascript unit-testing tdd


【解决方案1】:

你应该这样做:

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】:

    您的函数似乎将返回单词列表中“单词”的索引。这意味着,您的函数必须接收 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;
    };
    

    【讨论】:

      猜你喜欢
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多