- Azure Mobile Services, a mobile backend-as-a-service, is written in Node.js
What are unit tests?
Let's make sure we're all on the same page. A unit is a small section of code. Unit testing means you test that bit of code to make sure it functions properly. This increases confidence in your code.
Unit tests are important when many people work on the same codebase. If one engineer changes code in one part of the project, you want to ensure that the rest of the project still works.
Guiding principles for unit tests
- Predictable. If you have a certain input, you should always get the same output. Your input should always be static. For example, don't pass a random number or the current time as an input.
- Pass or fail. It should be obvious if your test passed or failed.
- Self documenting. Your code should describe what the test is meant to do. Another engineer looking at your test should immediately be able to understand it. It helps if you use testing and assertion frameworks which read like English.
- Single responsibility. Unit tests should only test one single thing at a time. If you want to test more things, then write more unit tests.
- Useful error messages. When a unit test fails, the error message should be useful.
- Not integration tests. Unit tests don't test multiple components. Unit tests come first, then integration tests, then validation tests.
- Too busy. "I have too many other things to do." "There's plenty of time after development to catch bugs." When you fix a bug and it breaks something else, it's called a regression. Unit tests can prevent regressions.
- Too hard. "It's too difficult to write unit tests." "It'll take too long because I'm not experienced."
- Too confident. "I don't need unit tests. My code works." "Why waste time writing unit tests because my code works?"
- Too lazy. "There are other things I'd rather be doing." "I just don't want to write unit tests."
- Too cumbersome. "It takes too long to run the unit tests." "I keep forgetting to run the unit tests."
If you find yourself making one of the excuses above, do yourself a favor and work to get over it. Like anything, there's a bit of a learning curve. However, you'll save yourself countless frustrating hours down the road if you put in a little time now to learn this. It's not as burdensome as you might think.