Node.js testing for multiple environment variables
Node.js testing for multiple environment variables
I recently added S3 support to my image serving microservice. Thanks to it, images uploaded to the service can be stored in an S3 bucket as opposed to a local folder. However, as some users might not want to use the feature, I made it so that is can be enabled by setting a specific environment variable, namely S3_BUCKET.
However, as both local storage and S3 storage cannot be both enabled at the same time, the Mocha tests I had written could not cover the whole code of the application in a single run.
To solve, this problem, I created two scripts in the package.json: One to run the tests with the S3_BUCKET variable set and the other one without, leveraging the option to prefix environment variables to the command:
"scripts": {
"test": "mocha -r ts-node/register test/*test.ts --exit",
"test-local": "S3_BUCKET= npm run test",
"test-s3": "S3_BUCKET=test npm run test",
"test-all": "npm run test-local && npm run test-s3",
"coverage": "nyc npm run test-all --exit"
},
With this approach, the application is tested twice, once with the S3_BUCKET variable set and once without, which is also reflected in the coverage report generated by nyc.