This post serves as an introduction to testing a Node.js RESTful API with Mocha (v2.3.1). a JavaScript testing framework.
Why Test?
Before diving in it's important that you understand why tests are necessary.
Grab the Node/Express sample CRUD application from the repository:
Once you have v1 of the app, manually go through it and test each of the CRUD functions via cURL (or HTTPie or Postman):
- Add new blobs
- View all blobs
- View a single blob
- Update a single blob
- Delete a single blob
This is a tedious process. What if you had to go through this same manual processevery single time a new feature got added to the application? That would not only be a massive misuse of time - but unreliable as well. Hence the need for setting up a testing framework for automating the testing of the application, so you can run hundreds of tests in a matter of seconds.
With that, install Mocha:
We installed this globally so we'll be able to run
mocha
from the terminal.
Structure
To set up the basic tests, create a new folder called "test" in the project root, then within that folder add a file called test-server.js. Your file/folder structure should now look like:
Now add the following code to the new file:
Although this is just boilerplate, pay attention to the describe()
block and it()
statements. describe()
is used for grouping tests in a logical manner. Meanwhile, the it()
statements contain each individual test case, which generally (err, should) test a single feature or edge case.
Logic
To add the necessary logic, we'll utilize Chai (v3.2.0), an assertion library, and chai-http (v 1.0.0), for making the actual HTTP requests and then testing the responses.
Install them both now:
Then update test-server.js, like so:
Here, we required the new packages, chai
and chai-http
, and our app.js file in order to make requests to the app. We also used the should
assertion library so we can utilize BDD-style assertions.
One of the powerful aspects of Chai is that it allows you to choose the type of assertion style you'd like to use. Check out the Assertion Style Guide for more info. Also, aside for the assertion libraries included with Chai, there are a number of other libraries available via NPM and Github.
Now we can write our tests…
Test - GET (all)
Update the first it()
statement:
So, we passed an anonymous function with a single argument of done
(a function) to the it()
statement. This argument ends the test case when called - e.g., done()
. The test itself is simple: We made a GET request to the /blobs
endpoint and then asserted that the response contained a 200 HTTP status code.
Simple, right?
To test, simply run mocha
; and if all went well, you should see:
Since testing the status code alone isn't very significant, let's add some more assertions:
This should be straightforward, since these assertions read like plain English. Run the test suite again. It passes, right? This test still isn't complete, since we're not testing any of the actual data being returned. We'll get to that shortly.
How about testing a POST request…
Test - POST
Based on the code within index.js, when a new "blob" is successfully added, we should see the following response:
Need proof? Test this out by logging
{'SUCCESS': newBlob}
to the console, and then run a manual test to see what gets logged.
With that, think about how you would write/structure your assertions to test this…
Need help understanding what's happening here? Add console.log(res.body)
just before the first assert. Run the test to see the data contained within the response body. The test we wrote tests the actual structure and data from the response body, broken down by each individual key/value pair.
Hooks
Up to this point we have been using the main database for testing purposes, which is not ideal since we're polluting the database with test data. Instead, let's utilize a test database and add a dummy blob to it to assert against. To do this, we can use thebeforeEach()
and afterEach()
hooks - which, as the names suggest, add and remove a dummy document to the database before and after each test case is ran.
This sounds a bit difficult, but with Mocha it's super easy!
Start by adding a configuration file called _config.js to the "server" folder in order to specify a different database URI for testing purposes:
Next, update app.js to utilize the test database when the environment variableapp.settings.env
evaluates to test
. (The default is development
.)
Finally, update the requirements and add the hooks to the testing script:
Now, before each test case, the database is cleared and a new blob is added; then, after each test, the database is cleared before the next test case is ran.
Run the tests again to ensure they still pass.
Test - GET (all)
With the hooks set up, let's refactor the first test to assert that the blob from thebeforeEach()
is part of the collection:
Let's look at the final three tests…
Test - GET (single)
In this test case, we first added a new blob, and then used the newly created _id
to make the request and then test the subsequent response.
Test - PUT
Here, we hit the /blobs
endpoint with a GET request to grab the blob added from the beforeEach()
hook, then we simply added the _id
to the URL for the PUT request and updated the name to Spider
.
Test - DELETE
Finally…
Conclusion
Hopefully you can now see just how easy it is to test your code with Mocha and Chai. Keep practicing on your own, incorporating a true BDD approach into your workflow. Grab the final code for this tutorial from the repository.