DEV Community

Sadick
Sadick

Posted on • Originally published at hackernoon.com on

Learn Assert by building a javascript testing library

Building interesting projects with nodejs standard lib.

One way you can learn about node js is by building stuff. A lot of developers say they know Nodejs because it is just javascript on the server side, but many of them don’t know how to use the nodejs standard library. Lets start by working with the assert library and build a simple testing library.

A testing library is a piece of software that helps us test out our code to ensure that it is working correctly as intended. An example of a testing library is Jest by Facebook. We are going to borrow the structure of how jest tests are written.

Starting with the simplest examples. Assuming that we have a piece of code that sums two numbers.

How will the intended testing code be.

Laying out the structure of the testing library.

As you can see from the structure there is nothing fancy, just functions. We are going to use assert in the expect function. Assert is used for assertion.

We want to be able to make assertions like expect(4).toEqual(10) and we are going to make use of the assert lib available in the node js standard library.

Lets look at the assert functionalities we have used in the expect function

assert.ok :- Asserts that any expression passed to ok evaluates to a truthy value failure to which an error will be thrown.

assert.equal :- Asserts that two values are equal, if not an error will be thrown

assert.deepStrictEqual :- Asserts that two objects, or their child objects, are equal, an error is thrown if they are

We need a way to show error and success states when tests pass or fail. We will use just a simple try catch block in the it function.

Here is the complete source code.

Am a strong believer that you learn by doing. I have left out a couple of things that you can use to practice. There are many things you could do to make it better and here are two things to get you started.

  • Color the output of the tests (passing — green, failing red)
  • If the test fail, show values of the expected and actual values passed.

Take your time to implement the two features and when you are done, hit me up on twitter for review. And also if you are stuck you can reach out to me I will be happy to assist.

If you found this post helpful, please give a clap and share it so that others can find it. You can follow me on GitHub and LinkedIn. If you have any ideas or improvements feel free to share them with me.


Top comments (0)