- Building Enterprise JavaScript Applications
- Daniel Li
- 416字
- 2021-07-23 16:31:24
Removing hardcoded values
Since we are only running these tests locally for now, we can simply hardcode the host name of our local API server, which we've set to http://localhost:8080/. However, it's never ideal to hardcode values into our code, as when we want to run these same tests on a different server, we'd have to edit the code itself.
Instead, we can make use of environment variables, which we can set in an .env file at the project root directory and load it when we run our tests.
Create a new .env file and add in the following entry:
SERVER_PROTOCOL=http
SERVER_HOSTNAME=localhost
SERVER_PORT=8080
Next, we need to load the environment variable into our code. We can use the dotenv-cli package (https://www.npmjs.com/package/dotenv-cli) to do this:
$ yarn add dotenv-cli --dev
To use the dotenv-cli package, you simply place dotenv in front of the command you want to run, and it will load the variables from the .env file and then run the command:
dotenv <command with arguments>
So, let's change our serve and test:e2e npm scripts to use the dotenv-cli package. Note that we are using a double dash (--) to pass the flags into cucumber-js after dotenv has finished loading the environment variables:
"serve": "yarn run build && dotenv node dist/index.js",
"test:e2e": "dotenv cucumber-js -- spec/cucumber/features --require-module @babel/register --require spec/cucumber/steps",
Then, in our code, remove the hardcoded hostname and replace it with the environment variable:
this.request = superagent('POST', `${process.env.SERVER_HOSTNAME}:${process.env.SERVER_PORT}/users`);
Again, we should run the tests to ensure they pass:
$ yarn run test:e2e
......
1 scenario (1 passed)
6 steps (6 passed)
Lastly, the point of using environment variables is that different environments would have different settings; therefore, we shouldn't track the .env file in Git. However, we do want to keep a record of what environment variables are supported, and so we should copy our .env file into a new .env.example file and add that into our Git repository:
$ cp .env .env.example
We have now implemented a new feature that is functional for a single scenario; this is a good time to commit our code to the Git repository. Remember that we had previously made a WIP commit. So now, instead of running git commit, we should add an --amend flag, which will overwrite and replace our previous commit:
$ git add -A
$ git commit --amend -m "Handle create user calls with empty payload"