Kaigai Blog living abroad in my twenties

【My Study Note】What is TDD (Test Driven Development)

JavaScript Programming

What is TDD (Test Driven Development)

What is TDD (Test Driven Development)

Definition

It’s a streamlined process of writing code that will satisfy some requirements.

What’s the process?

  • 1. Receiving requirements which will become a feature of the app that’s being developed (Request about what kind of function the clients want you to create)
  • 2. Writing a failing test for that to build feature before it gets built. (Write a test code and test it which would be “red” for sure since you are not writing any code about that in the main file.)
  • 3. Making this failing test pass by coding that given feature.
  • 4. Refactoring (機能自体は変えないように、ソースコードを書き直したり整理したり無駄なコードを削除することで見やすくする)

Comparing to the traditional development process, the TDD approach is somewhat upside down. 

普通は、コードを書いてからそれをテストし、その後で修正する。でもTDDでは、テストコードを先に書いて、テストし(もちろん、まだ本物のコードは書いてないから通らない)、テストを通過する為に必要な最低限のコードを本物のコードに付け加える。

Example

Step1: Write the test code which matchs the requirement

test('return true if statusOfKeys exists', ()=> {
    expect(statusOfKeys).toBeDefined();
})

And after this, try testing. But of course, it cannot be passed.

Step2: Define the fucntion in your source code so you can pass the test

function statusOfKeys(){}

And you can pass the test since you define the function.

It’s important to note that one of the rules of TDD is that you should write as little code as possible to make the test pass for this test to pass, that’s why, it’s enough to just declare a function with the name.

Benefits of using TDD

  • Minimizing regressions that are accidental bugs introduced to old code by coding a new requirement
  • Proof that your new implementation is not breaking other parts of the app
  • You can automate these tests easily and thus keep verifying again and again that the system works as expected.
  • You can test your implementations with various inputs
  • Tests become a specific kind of documentation for the new members of your team. Because it’s tracking everything

Making sure that all the tests are passing is a strong signal that the current requirement and all the previous requirements for this piece of your app have been delivered successfully and that nothing is breaking.