Continuation from http://justcodesnippets.durlut.ro/index.php/2019/12/08/node-js-image-delivery-microservice-challenge-mongo-db-stats-page/
Using some inspiration from here: https://buddy.works/guides/how-automate-nodejs-unit-tests-with-mocha-chai we start creating out unit tests:
First we install mocha and chai npm install mocha chai --save-dev
Then we install request npm install request --save-dev
Then we install request npm i @types/mocha
This is not enough to run the test as we need to do a setup in package.json as said here: https://stackoverflow.com/a/50903056/249895
We also have to set the test as below:
"scripts": {
"prebuild": "tslint -c tslint.json -p tsconfig.json --fix",
"build": "tsc",
"prestart": "npm run build",
"start": "node .",
"test": "mocha src/test/*.ts",
"smoketest": "mocha smoketest/**/*.ts"
}
We are having issues running th test so we take another look here: https://42coders.com/testing-typescript-with-mocha-and-chai/
We re-install the packages npm install chai mocha ts-node @types/chai @types/mocha --save-dev
The test line looks like this now: "test": "mocha -r ts-node/register src/test/*.ts",
We are still having issues with assetions so we install chai-http npm install chai-http
A wild error pops up: Uncaught TypeError: Cannot read property 'statusCode' of undefined
We are still having issues with async calls so we will test something less dififcult: the validator.
We run npm test
We get passing tests.