In this tutorial we are going to write a simple RESTful API with Node.js and use Mocha and Chai to write tests against it. We will test CRUD operations on a bookstore.
I still remember the satisfaction of being finally able to write the backend part of a bigger app in node and I am sure many of you do it too.
And then? We need to make sure our app behaves the way we expect and one of the strongly suggested methodologies is software testing. Software testing is crazily useful whenever a new feature is added to the system: Having the test environment already set up which can be run with a single command helps to figure out whether a new feature introduces new bugs.
As usual you can build the app step-by-step throughout the tutorial or directly get it on github.
Mocha comes with tons of great features, the website shows a long list but here are the ones I like the most:
So with Mocha we actually have the environment for making our tests but how do we do test HTTP calls for example? Moreover, How do we test whether a GET request is actually returning the JSON file we are expective, given a defined input? We need an assertion library, that’s why mocha is not enough.
So here it is Chai, the assertion library for the current tutorial:
Chai shines on the freedom of choosing the interface we prefer: “should”, “expect”, “assert” they are all available. I personally use should but you are free to check it out the API and switch to the others two. Lastly Chai HTTP addon allows Chai library to easily use assertions on HTTP requests which suits our needs.
What is REST? The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used
In this tutorial, you will learn the fundamentals of RESTful API design by applying REST principles and best practices. In additon, learn how to define resources, methods, requests, and responses.
Conceptualizing REST through a practical and objective approach. The goal of this article is to show off elements of the web architecture that are fundamental pieces of REST architecture.
When you need to build an API, your mind will likely jump to REST, the de facto standard for API creation. However, this is about to change with GraphQL, as its popularity quickly rises.
Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.