Creating unit tests for Node.js using the Mocha testing library
The base of our testing pyramid is made of unit tests. These tests are highly componentized, individual functionality tests that simply ensure that a unit of code, such as a route or some middleware, conforms to its expected API and handles failure cases as expected. Unit tests don't generally rely on other aspects of our application, and rely on extensive mocking of application states and data structures to test functionality instead. Testing individual methods and business logic in our application, such as our Express application middleware, makes for great unit tests.
Getting ready
Let's explore how to apply unit testing using the popular Mocha
and Chai
Node.js libraries to our Express web server. Before we start, we'll want to ensure that we install these libraries and their TypeScript type definitions to our application's package.json
file:
npm install mocha chai @types/mocha @types/chai --save-dev
In keeping with our convention...