Lesson #0 - Test Driven JavaScript Development Basics

A unit test is an automated piece of code that invokes a unit of work in the system and then checks a single assumption about the behavior of that unit of work. A unit of work is a single logical functional use case in the system that can be invoked by some public interface (in most cases).

Or in human language, a unit test which tests code that has been isolated down to a point where external dependencies are not a concern.
Any external dependency should faked out or the code should be refactored so it doesn't depend on the external dependency.

What to Unit Test

Test code that you, or your team has written. Write tests to test the business rules. You don't need to test JQuery. You don't need to test if the correct events are attached to the DOM. You don't need to worry about AngularJS rendering your code right.

How Far Should You Test

Focus on writing tests to invoke "public" methods. These are methods the DOM will call, or if you have a JavaScript class, is exposed publicly. Don't test "private" or "internal" methods. This makes your tests brittle and makes your code very tricky to refactor.

Disclaimer: I am aware all JavaScript methods are public, but there are a few tricks you can do to indicate they are private.

Avoid Too Much Setup

If a unit test requires dozens of lines of setup code something might need to be refactored or faked out.

Mocks vs Stubs

Mock - asserted against

Stub - not asserted against

A stub is used when your code requires data from an external dependency. How your code handles and manipulates the data is what you need to test. A mock is asserted against. An example would be an AJAX call. You would assert against a Mocked AJAX call to make sure the data sent is correct. An object could be a stub in one test and a mock in another test.