Building a Unit Test in Jasmine, Part 2

In the previous part, I showed an extremely simple test whose only purpose is to highlight how Jasmine works. This post will take those pieces and start doing something more dynamic with our source code. The Source and the Spec are going to change.

One reason to unit test is to confirm your code works despite internal changes to the source. As your application changes and matures, it can be daunting to ensure your old code still works. Properly created and maintained unit tests make this much less scary. You add a feature, run all your tests. Everything passes, then you are in good shape. If something breaks, you know it now and not when the customer finds it. Once everything passes you can move on to your next set of changes with relative certainty your application still works.  This post will set us up to show that principle in action over the next 2 posts.

The first change we are going to make is to create a source. We are using a JSFiddle to keep everything located in one place for easier review.  In true practice, the source code is a separate file or files.  At this point, I try to think of tests in terms of objects and functionality, not the files that hold them.  Ultimately, where your source files live will be dictated by the system being tested.

Our source code is going to be a simple type with a constructor and a function.  The object constructor will receive a literal with 2 properties: a and b. Those values are then assigned to internal properties, number1 and number2, on the JasmineTester object.  The total function will take the JasmineTester's internal number1 and number2 properties and add them together, then return the result.

Our changes to the spec are going to be minor.  The spec makes a new JasmineTester object, called testObject, and passes in a=2 and b=2.  Our expectation is that calling testObject's total function will return 4. The total function does indeed return 4.  Test passed!

Our next steps will be to enhance the JasmineTester's constructor function to handle multiple incoming values.  However, this test will be unchanged.  We will add to the spec as we go along, but this simple test will remain as is.  This is how it should be in regular production environments.  The tests you made in the beginning should continue to pass through most code modifications (system level re-writes and architecture overhauls will require new tests).

If this was real production code, and we needed to enhance JasmineTester 6 months from now, this simple test would let us know that code built to use the current JasmineTester object still worked.