There are multiple unit testing libraries for node and the one I’ve used in the past was Mocha, but I’ve taken a different approach lately and started using the NodeUnit library, which can be found here. I like this library for being so incredibly simple and quick to set up. You can start writing unit test immediately using just the tools on your command line to execute them or pull the library into a local file to execute from there. For this example include “nodeunit” in your package.json so that we can create a reporter and execute one file to run all of our tests.
To start writing unit test the first step is to create a home for our test to live. This is typically done in a /test folder within the root of the project.
Lines 3 and 4 simply set up our global variables to be used. Line 3 is the standard file system util that comes with node.js and line 4 creates a Node Unit reporter. The reporter object runs a collection of Node Unit tests. Node Unit includes a variety of reporters and the ability to create your own, but for this example we just need the default reporter to run these test.
Line 6, sets up our initialize function and within this function, we want to check every file in our current directory (line 10) and filter out all test files and add it to our collection of tests.
All unit tests in nodeunit are simply an object which includes our test. We have three functions within this module: setUp, createUserTest, and authorizeUserTest. The setUp function will be called before each test by nodeunit, we need this function to setUp the connection to our database and sync our models with Sequelize so that the controller functions can flow as normal. If anything is passed back to the callback function in setUp the test will automatically fail. Each test in nodeunit is run in a series by order of definition so first, we’ll want to create a user here and then test whether we can authorize our user properly. Since this controller is a node endpoint we need to pass in a request and response to properly call the methods. That ResponseFactory object is a simple utility class to return a mock response object. Now when going to the terminal and execute this test by calling “node init.test.js” we will see the following output.
I went ahead and changed the password in the authorize test to be something invalid and we will see the following output.
I could write another unit test in this file to include this as a failure and test the error response to be invalid and make sure my fail conditions fail properly as this one just did. Basically, any type of response that goes on in your application should theoretically have a unit test associated with it, and it’s good to have something you can reliably run to expose issues correctly before they show up in production.