Running tests in a test database

For our project, let's use the index name hobnob for development, and test for testing. Instead of hard-coding the index name into our code, we can use an environment variable to set it dynamically. Therefore, in both our application and test code, replace all instances of index: 'hobnob' with index: process.env.ELASTICSEARCH_INDEX.

Currently, we are using the dotenv-cli package to load our environment variables. As it turns out, the package also provides an -e flag that allows us to load multiple files. This means we can store default environment variables in our .env file, and create a new test.env to store testing-specific environment variables, which will override the defaults.

Therefore, add the following line to our .env file:

ELASTICSEARCH_INDEX=hobnob

Then, create two new files—test.env and test.env.example—and add the following line:

ELASTICSEARCH_INDEX=test

Lastly, update our test script to load the test environment before the default:

"test:e2e": "dotenv -e test.env -e .env cucumber-js -- spec/cucumber/features --require-module @babel/register --require spec/cucumber/steps",

Stop the API server and restart it with the following command:

$ npx dotenv -e test.env yarn run watch

Run our E2E tests again, and they should all pass. The only difference now is that the tests are not affecting our development index at all!

Lastly, just to tidy things up, let's move all our environment files into a new directory called envs and update our .gitignore to ignore all files with the .env extension:

$ mkdir envs && mv -t envs .env .env.example test.env test.env.example
$ sed -i 's/^.env$/*.env/g' .gitignore

Of course, you also need to update your serve and test scripts:

"serve": "yarn run build && dotenv -e envs/.env node dist/index.js",
"test:e2e": "dotenv -e envs/test.env -e envs/.env cucumber-js -- spec/cucumber/features --require-module @babel/register --require spec/cucumber/steps",

Run the tests again and make sure they pass. Once you're happy, commit these changes to Git:

$ git add -A && git commit -m "Use test index for E2E tests"