Writing Code with TDD
test.js
When practicing test-driven development (TDD), you always begin by writing a test that describes the behavior you want from your code before you actually implement the feature. In the code above, you start by writing a test for a capitalize function that should take a string and return it with the first letter in uppercase. At this point, the function does not exist yet, so the test will fail. This is an important part of the TDD cycle because it confirms that your test is correctly set up and that the feature is not already implemented.
Next, you write just enough code to make the test pass. In this example, you implement the capitalize function so that it takes the first character, makes it uppercase, and adds the rest of the string. After this change, running the test should result in a passing test.
The final step in the TDD cycle is to refactor your code. This means you look for ways to improve the code without changing its behavior. You might clean up variable names, remove duplication, or optimize logic. In this simple example, the function is already straightforward, so no further changes are needed. By following these steps—write a failing test, make it pass, then refactor—you ensure your code is both reliable and maintainable.
1. In TDD, what should you do after making a failing test pass?
2. Why do you start with a failing test in TDD?
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 7.14
Writing Code with TDD
Swipe to show menu
test.js
When practicing test-driven development (TDD), you always begin by writing a test that describes the behavior you want from your code before you actually implement the feature. In the code above, you start by writing a test for a capitalize function that should take a string and return it with the first letter in uppercase. At this point, the function does not exist yet, so the test will fail. This is an important part of the TDD cycle because it confirms that your test is correctly set up and that the feature is not already implemented.
Next, you write just enough code to make the test pass. In this example, you implement the capitalize function so that it takes the first character, makes it uppercase, and adds the rest of the string. After this change, running the test should result in a passing test.
The final step in the TDD cycle is to refactor your code. This means you look for ways to improve the code without changing its behavior. You might clean up variable names, remove duplication, or optimize logic. In this simple example, the function is already straightforward, so no further changes are needed. By following these steps—write a failing test, make it pass, then refactor—you ensure your code is both reliable and maintainable.
1. In TDD, what should you do after making a failing test pass?
2. Why do you start with a failing test in TDD?
Thanks for your feedback!