So you can change code with confidence. You know what works and what shouldn't. You don't fear refactoring in an area covered by unit tests.
Tests aid you in understanding and covering requirements... especially if you start by writing tests - see TDD.
Tests aid you in finding flaws in your code or even in your design.
Tests can also serve as documentation (especially if you write them with BDD style assertions).
Plus, they don't go out-of-date, unlike separate documentation, which can and frequently does.
Testing is fun. (ノ◕ヮ◕)ノ*:・゚✧
Because it's a good idea to write unit tests, and because we can.
。◕‿◕。
The days of untestable spaghetti code on the client are gone (thanks frameworks!)
Divide and conquer.
Split and isolate business logic from UI logic.
Don't intermingle responsibilities.
Write small functions instead of one big one. Small functions are easier to test.
However, don't go to overboard on this, make sure your functions extractions make sense from a separations of concerns perspective - you don't want to ruin the design just to make it easier to test.
If you're working on a new feature and you don't know where to start...
Start by writing unit tests. You don't necessarily need to fill them out, setting up the basic structure can help you figure out what you need to do and start coding.
This is a way to get some of the benefits of TDD, without fully committing to it ;)
A good unit test is very limited in scope. If the test fails, it's obvious where to look for the problem.
Use as few assertions as possible so that the offending code is obvious. It's important to only test one thing in a single test.
Don’t test what has been tested already: meaning don't test what the framework / library you use do out of the box.
Test domain specific stuff, like business rules, etc. Tests should be relevant and meaningful.
Beware of false positives.
This might not be a problem in server-side unit testing frameworks,
but it is one in Mocha
for example (due to the way JavaScript works).
However there are solutions out there.
Don't give up!
Preexisting code created without tests can be challenging to test/refactor, but with
incremental effort, it can be done.
If you find something that is hard to test, see if it can be refactored.
Improving code quality can be a nice side-effect of unit testing.
Aim for good code coverage and well-written tests, but don't let yourself become overly concerned with them.
After all...
"Imperfect tests, run frequently, are much better than perfect tests that are never written at all". - Martin Fowler