Test-driven development (TDD) is a software development process which relies on the repetition of a very short development cycle. In JavaScript, TDD consists of three main steps:
1. Write a failing test: The developer firstly writes a test for the new feature or functionality before writing the code. At this stage, the test will fail because the code for the feature doesn’t exist yet.
1. Make the test pass: The developer then writes the minimal amount of code necessary to make the test pass. The code might not be perfect and could include some redundancy.
1. Refactor the code: Now that the test is passing, the developer can improve and refactor the code while keeping the test green (passing).
This process encourages simple designs and inspires confidence. The purpose of TDD is to make the code clearer, simpler and bug free. It is regularly used in JavaScript and is supported by testing frameworks in JS like Jest or Mocha.
In essence, TDD is about managing fear during programming, fear that pieces of the code may break, fear that you may break it if you add new functionality, and fear you dare not refactor because you cannot tell what you might affect. By using TDD, you eliminate that fear and are driven to improve, adapt or refactor the code. You gain confidence it behaves as anticipated when you run the tests against your code. Therefore, Test-driven development approach requires that developers think about the requirements or design before writing their code to ensure their code is of higher quality, more reliable, and more maintainable.