Arrange-Act-Assert

When building tests for any piece of code, a very common approach to follow is that of Arrange-Act-Assert. This describes the different steps that take place inside a single unit test.

The first thing we do is set up a test scenario (arrange). This step can consist of a number of actions and may involve putting in place fake objects to simulate real objects as well as creating new instances of the subject under test. If you find that your test setup code is long or involved, it is likely a smell and you should consider refactoring your code. As mentioned in the previous section, testing is helpful for driving not just correctness but also architecture. Difficult-to-write tests are indicative that the architecture is not sufficiently modular.

Once the test is set up then the next step is to actually execute the function we would like to test (act). The act step is usually very short, in many cases no more than a single line of code.

The final part is to check to make sure that the result of the function or the state of the world is as you would expect (assert).

A very simple example of this might be a castle builder:

class CastleBuilder {
  buildCastle(size) {
    var castle = new Castle();
    castle.size = size;
    return castle;
  }
}

This class simply builds a new castle of a specific size. We want to make sure that no shenanigans are going on and that when we build a castle of size 10 we get a castle of size 10:

function When_building_a_castle_size_should_be_correctly_set() {
  var castleBuilder = new CastleBuilder();
  var expectedSize = 10;
  var builtCastle = castleBuilder.buildCastle(10);
  assertEqual(expectedSize, builtCastle.size);
}

Assert

You may have noticed that in the last example we made use of a function called assertEquals. An assert is a test that, when it fails, throws an exception. There is currently no built-in assert functionality in JavaScript, although there is a proposal in the works to add it.

Fortunately, building an assert is pretty simple:

function assertEqual(expected, actual){
  if(expected !== actual)
  throw "Got " + actual + " but expected " + expected;
}

It is helpful to mention, in the error, the actual value as well as the expected value.

There is a great number of assertion libraries in existence. Node.js ships with one, creatively called assert.js. If you end up using a testing framework for JavaScript it is likely that it will also contain an assertion library.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.209.131