DEV Community

Daniel Werner
Daniel Werner

Posted on • Originally published at danielwerner.dev on

Testing with Mocha – 4. Testing error handling

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!')
    }

Enter fullscreen mode Exit fullscreen mode

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


     assert.throws(
          () => collection.push("4"),
          TypeError
      );

Enter fullscreen mode Exit fullscreen mode

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,


collection.push(4)

Enter fullscreen mode Exit fullscreen mode

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


         assert.doesNotThrow(
              () => collection.push(4),
              TypeError
          );

Enter fullscreen mode Exit fullscreen mode

Check out all posts in the series Testing with Mocha.

The post Testing with Mocha – 4. Testing error handling appeared first on Daniel Werner.

Discussion (0)