This post will cover testing REST API's built with Express.JS, using Mocha as the test framework. Express and Mocha are both by the same author and work well together. This technique can also be used to test Express apps in general.
In a nutshell, we'll create a test suite in Mocha that does the following:
- instantiates and runs our REST API server (an Express app)
- sends HTTP (or HTTPS) requests to the REST API
- checks the responses for appropriate values
Our example test suite is a file located at test/app_test.js. The first thing you'll need to do is include the Express app you want to test. Mine is simply called app.js, so this is what the start of my test suite looks like:
Before we can start testing our API server app we need to start it. We can create a test suite called "app" for this. Before anything, we'll start the app. Then we'll check to make sure it is running. Here's what it looks like:
There are a couple of pieces missing from the test case above. We're using Node's build-in http library, so we need to include that at the top of our file as well:
And, there's a function defaultGetOptions, which is just a little helper utility to format our request:
Lastly, you can see that there's a variable called sessionCookie. This is how we maintain a session with our REST API, in case your API requires an authenticated session. You can simply declare this variable at the top of the file:
And set the cookie value whenever you get a response from the API server. Here is an example of setting the sessionCookie value when logging in:
As you can see, I'm using a few extra variables or functions - there are some test-user parameters, and a function to format the headers for a POST request. Having seen the example for a GET request, you should have no problem creating similar functions for POST, PUT, and DELETE (check out the Node docs for HTTP).
Finally, to make this all work you might need to modify your Express app to make sure that it does not start up automatically on the default port, if it is being included as part of a test suite. You do this by checking for module.parent.
Above, you can see that the app will only start actively listening if it is being run directly, but if it has been included in a test suite like ours, it won't automatically start up. This let's us start the app on a port of our choosing from within our test suite, like we did in the example above.
Hope that helps...