Express API project starter files with unit tests
Here's what I've come up with for getting started with an Express API project that includes unit tests:
Here's a quick summary of the starter files:
src
app.js - defines the Express application (and exports it)
server.js - imports app.js and starts it
tests
api.test.js - imports app.js and starts it in order to run test requests
sample.test.js - use it as a starter file for testing app components
.env - defines environment variables for production mode
.env.dev - defines environment variables for dev mode
.env.test - defines environment variables used while running tests
Note that the app code (app.js) and the code that starts the app (server.js) have been separated into different files so that we can import app.js into the api.test.js file (which starts the app via supertest).
Start by installing the dependencies:
npm install
You also need to have the dotenv-cli package installed globably:
npm install -g dotenv-cli
The scripts that are defined in package.json
To run the unit tests (note that this will use the .env.test file):
npm run test
To run the app in dev mode (using the .env.dev file):
npm run dev
To run the app in production mode (using the .env file):
npm run start