Testing with Mocha – 4. Testing error handling

Published at: 2021-04-20 06:46:20

In this post we will take a look how can we expect that an error is thrown and how to make sure no error is thrown when when everything should be fine.

Asserting an error is thrown

Let’s take a look on how to make sure the expected error is thrown in case when we need it. As an example lets extend our generic collection class, and create a specific collection which can store only numeric values.

See the Pen Testing with Mocha – Example 4.1 by Daniel Werner (@daniel-werner-the-decoder) on CodePen.

As we can see in the example above, the numeric collection throws and error when we try to push a non numeric value in it.

    if (typeof item !== 'number') {
        throw new TypeError('Numeric collection can only store numbers!')

In the test we make sure, that this specific error occurs when we try to push a string to our numeric collecion.

          () => collection.push("4"),

Asserting an error is not thrown

As we’ve seen in the previous example we can assert that a specific error is thrown when necessary. We can also make sure that the error is not thrown when everything should work fine. The following example shows that the numeric collection accepts an integer value without throwing the type error.

See the Pen Testing with Mocha – Example 4.2 by Daniel Werner (@daniel-werner-the-decoder) on CodePen.

As you can see, this example is almost the same as the previous. The only important difference is that we pushed an integer to the numeric collection,


and we asserted that the code does not throw a TypeError:

              () => collection.push(4),