Testing with Mocha – 2. Using the assert library

In the previous lesson we’ve created our first test, but used only one assertion to check if the result equals to a predefined value. Let’s take a look at the capabilities of the Chai’s assert library, and explore them through some more advanced examples.

Using strictEqual and notStrictEqual

In the first example we’ve already used the equal assertion. The basic difference between equal and strictEqual is that the latter compares the types as well. The strictEqual only accept the value if it’s type and value is the same as the expected one.

Let’s see and example of how to use the strictEqual. We’ll use the example from the previous lesson and assert that our sum method return the correct result, this time type checking. Also we add a new functionality to the sum method, if it encounters a non numeric item in the data, it returns null. We’ll also create a test for that.

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

Sometimes we may want to assert that the result of a method call does NOT equal to a given value. In our example the sum method can return a number when the sum is successful or null if it is not. Let’s create an assertion that it never returns false.

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

Comparing objects

We’ll continue to develop our collection class from the previous lesson, add more features to it and learn the other assertion types.

The assert.deepStrictEqual

The equal assertion cannot be used on object, like our collection. For this purpose we can use the deep strict equal assertion. It checks the objects own enumerable properties, and strictly checks their types.

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

As we saw in the previous example if the assertion fails when only the type differs in the data. Let’s see another use case for this. We’ll add a push method to our collection. The push method can be used to add new element to the collection.

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

As we can see from the above example, we use the push method to add a new element to the collection, and use the deepStrictEqual to make push method works correctly, and the collection has the same elements as expected.

let expectedCollection = new Collection([1,2,3,4])
              
              collection.push(4);
              assert.deepStrictEqual(collection, expectedCollection);

Check out all posts in the series Testing with Mocha.


  Follow me on on Twitter for more software development tips.