DEV Community

Discussion on: What are the Best Tips in implement TDD in a web application project

Collapse
 
leightondarkins profile image
Leighton Darkins

If you're an absolute beginner with TDD, and you're looking to get a feel for how it all works. I'd recommend getting familiar with the Red, Green, Refactor cycle.

Red: Write a test that fails.

it('returns 3 when given 1 and 2', () => {
  expect(calculator.sum(1, 2)).toEqual(3)
})
Enter fullscreen mode Exit fullscreen mode

Green: Write the minimum amount of code to make that test pass.

class Calculator {
  sum () {
    return 3
  }
}
Enter fullscreen mode Exit fullscreen mode

Refactor: Clean up the code you just wrote, if you need to.

then do it again...

Red:

it('returns 4 when given 2 and 2', () => {
  expect(calculator.sum(2, 2)).toEqual(4)
})
Enter fullscreen mode Exit fullscreen mode

Green:

class Calculator {
  sum (num1, num2) {
    return num1 + num2
  }
}
Enter fullscreen mode Exit fullscreen mode

Refactor: It's still pretty clean, so we won't.

Once you've got your head around that pattern. Have a look at something like this. Little, time-boxed, problems like these are great for building the habit of TDD.

An important thing to note here is that these examples are intentionally simple. Starting to write a .sum() method that just returns a fixed number doesn't make a whole lot of sense in the real world. But it helps to train your brain to start as simple as possible with your features and implementations. After a few runs through a few examples, you can just forget about starting that simple.

You can start working on these types of problems with just plain ol' JS and a test framework like Mocha or Jest.

If you're interested in a deep dive and you've got some spare cash, this is the book.

Collapse
 
jrking365 profile image
Jean Roger Nigoumi Guiala

Thank you, the Red Green Refactor technique summarize it all... :)