I am learning and practicing writing test with javascript:
Here is the test cases 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);
});
Here is my following function 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;
You should do this:
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);
});
Bit I think you need to remake the function, like this:
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;
If any of "expects" fails, all the test will fail
It seems your function will return the index of a "word" in a list of words. This means, your function has to receive 2 variables as parameters: "word" and "words".
I think the current function name (and filename) - findNeedle
is not "correct", so I recommended changing it. How about findWordIndex
?
The function logic is simple, you can use Array.indexOf
utility to do it, or do it in your way.
module.exports = (words, word) => words.indexOf(word);
Or
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;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.