Unit Testing Basics

Craig Freeman

Front-End Developer at Kenzan

What is unit testing?

"A software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper automation."


Often automated (almost always) automated.

Why do we do unit testing?

  • Reduce bugs in new/existing features
  • Make change affordable
  • Improve application design - Promotes:
    • High cohesion
    • Low coupling
    • More-modular code
    • Single level of abstraction
  • Confidence (or reduced fear) while developing and refactoring
  • Form of documentation - If you have trouble understanding code, try reading the unit tests to see what they are trying to enforce.

Why is unit testing hard?

Often because the code is poorly written (highly-coupled) and the programmer doesn't fully understand what the code is doing.

How do I unit test?

Programming is generally a series of small experiments - trial and error


When we don't have a clear picture of what we want to accomplish, the task could take a long time.

  • Take small steps (break down the problem)
  • Divide and conquer (simplify, de-couple)
  • Spike to learn

How do I unit test?

Positive Tests:

What do we expect to happen if the application is working?


Negative Tests:

What do we expect to happen if the application is not working?


Exception Tests:

What do we expect to happen if the application differs from what we expect?

How do I unit test?

Three A's:

Arrange - Act - Assert

// Arrange
var value = 9;

// Act
var result = doAwesomeThings(value);

// Assert

What should I be testing?

Canary test - make sure things are working

describe('awesomeFunction()', function () {
    it('should pass the canary test', function() {

What should I be testing?

Publicly-available methods and their interactions.


Private methods are generally implementation methods which are hidden from users and breaks encapsulation. Helper functions for the public functions.

What should I be testing?

Interactions with other methods should be mocked and those methods should have their own unit tests. 


Fakes, spies, mocks, stubs. Test-doubles to allow the test to concentrate on the main function without outside variables.

Test-driven development 



"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."

Test-driven development 


Red - Green - Refactor


  1. Add a test, it fails
  2. Write some code
  3. Run tests, it passes! Just barely...
  4. Refactor code. Apply design patterns as you see fit
  5. Repeat!


Prime factors





Unit Testing Basics

By Craig Freeman

Unit Testing Basics

  • 713
Loading comments...

More from Craig Freeman