An up-to-date 2020 example of how you can use Mocha and Chai to perform API testing for a Node-ExpressJS-Mongoose app.
Local testing and online automated testing
You will be able to test your code locally and also automatically when you push your code to Github, using Github Action.
Built for easy deployment
Furthermore, the code is set up such that it will automatically switch to Production Keys rather than Development Keys on deployment.
In this project, a single test suite: test/productRoutes.test.js is used to test a single Express route: routes/productRoutes.js which handles API calls pertaining to a single Mongoose model: models/Product.js.
Work-in-progress: Currently, there is only a single test case testing the 'GET /api/products' route. A full-fledge implementation and associated testing of
DELETE routes will be added by end March 2020.
Local testing guide
To deploy this project locally for development purposes, follow the steps below.
To begin, first install and set up the following.
- Install MongoDB locally, take note of your
mongoURI. Alternatively, you can use mLab instead.
- Install NodeJS.
- Clone this repository (e.g. enter
git clone https://github.com/DigiPie/mocha-chai-mongoose.gitin your command-line terminal).
Next, set up the NodeJS application with the following steps.
- Open the server sub-directory (folder) within the mocha-chai-mongoose folder you cloned (e.g.
- Install the required packages (which are specified in
package.json) by entering
- Open config/example_dev.js and fill in the
mongoURIto your development MongoDB instance.
Finally, you can execute the Mocha test suites under the test/ directory.
- Check that you are in the server sub-directory.
- Run this project on your local server by running
npm test(check out the
scriptssection in package.json for more info).
- To exit the test, press
CTRL + C.
Automated testing via Github action
Check out the Github Action workflow for this project: nodejs.yml. This workflow performs automated testing via
npm test each time you do a
git push to your Github repo.
- actions/checkout: to checkout this repo.
- actions/setup-node: to setup specified node versions.
- DigiPie/mongo-action: to instantiate a mongoDB server in a Docker container for testing against.
MongooseJS provides a straight-forward solution to modeling your NodeJS application data easily in MongoDB. It handles all MongoDB validation, casting and business logic on your behalf.
Chai is an assertion library for Node. We use Chai assertions and
chai-http in Mocha to perform HTTP testing of our NodeJS API endpoints.