Using Mocha for Test-Driven Development in building API with Node / Express
Automated tests? Why? How?
For the longest time, I was just writing functionalities and manually testing them to ensure they work as expected. Every single new functionality, I would test my service manually ten times, hundred times, THOUSANDS times… you get it.
Some of my key problems with manual testing were:
- Additional features may break existing functionality
- Code refactoring may break the intended logic
- No incentive to write clean code and maintainable code
- Huge waste of time, which could have been used to improve my application
I guarantee you that the extra effort put in writing tests will eventually pay off big time! So let’s get started!
What is TDD or BDD?
Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards.
The following sequence of steps is generally followed:
- Add a test
- Run all tests and see if the new one fails
- Write some code
- Run tests
- Refactor code
So TDD ensures that we write logic that is actually tested and is of high quality. BDD (Behavior-Driven Development) is based on TDD and promotes collaboration between product managers and developers.
Let’s say we have the following array:
var menu = [ 'green', 'chai', 'oolong' ];
In TDD, we will verify like so:
In BDD, we will instead write it like:
We can write more complex assertions but this is the gist of it. You can clearly see that BDD style is much…