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.
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) onCodePen.
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.
assert.throws( () => collection.push("4"), TypeError );
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) onCodePen.
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)
and we asserted that the code does not throw a TypeError:
assert.doesNotThrow( () => collection.push(4), TypeError );