Reputation: 379
I'm trying to learn how to write Test driven development and want to get good at it. I'm currently looking some practice on google and found this one but I don't know how to make this test pass.
Here is the test code add-one.test.js
:
var addOne = require("./add-one.js");
test("Add 1 to each item in myArray", function () {
var myArray = [31, 57, 12, 5];
var unchanged = [31, 57, 12, 5];
var expected = [32, 58, 13, 6];
var output = addOne(myArray);
expect(output).toEqual(expected);
expect(myArray).toEqual(unchanged);
});
add-one.js:
module.exports = function(numbers) {};
Upvotes: 0
Views: 49
Reputation: 57317
What normally happens in TDD is that we do the work in two steps. First, we prove that our test is working (by introducing a trivial change to the test subject that passes the test) and then we clean up the test subject until the code is not embarrassing.
return [32, 58, 13, 6]
Mark is exactly right that we can make the test pass that easily. We won't keep the code in that shape forever, but for now it gives us a starting point.
In some cases, we'll introduce a change in behavior behind a "guard clause" first, so that we can get an easy pass without breaking any other code
if numbers[0]== 31 && ... && numbers[3] == 5 {
return [32, 58, 13, 6]
}
Having done this, we're now in a situation where all of our tests are passing. So our goal is to clean up the code without breaking any of the tests.
"Remove duplication" is one of the themes of the changes that we make. In this example, there's a bunch of duplication between our input and our output.
return [31 + 1, 57 + 1, 12 + 1, 5 + 1]
return [numbers[0] + 1, numbers[1] + 1, numbers[2] + 1, numbers[3]+1]
return numbers.map(n => n+1)
Small steps shown here just to show how you might tease out the duplication in this case. You don't have to use the smallest possible steps every time; it's sometimes a useful skill to have.
Jumping straight to the form with the duplication already removed is OK too, if you can see it right away.
TDD is just a ritual for ensuring that your code is under your control. It doesn't actually tell you what changes to the code you should make. That comes from practicing design (and also learning what language/library features are available).
Upvotes: 2