There's one minor improvement we must make before we can do E2E testing with the API backend. At the moment, we are hard-coding the URL for our production API endpoint (localhost:8080), even though during the test, the testing URL (localhost:8888) will be used. Therefore, we need to replace this with a placeholder that we can override during build time.
First, in src/components/registration-form/index.jsx, replace the following line:
const request = new Request('http://localhost:8080/users/', {})
With this one:
const request = new Request('http://%%API_SERVER_HOST%%:%%API_SERVER_PORT%%/users/', {})
Next, we need to add a new loader to replace this placeholder at build time. string-replace-loader fits the bill perfectly. Let's install it:
yarn add string-replace-loader --dev
Then, inĀ .env and .env.example, add the details of the API host and port for different environment:
API_SERVER_PORT_TEST=8888
API_SERVER_HOST_TEST=localhost
API_SERVER_PORT_PROD=8080
API_SERVER_HOST_PROD=localhost
Then, use the plugin inside webpack.config.js. We want the loader to transform all .js and .jsx files, and so we can use the same rules that we used for babel-loader:
...
if (process.env.NODE_ENV === 'test') {
process.env.API_SERVER_HOST = process.env.API_SERVER_HOST_TEST;
process.env.API_SERVER_PORT = process.env.API_SERVER_PORT_TEST;
} else {
process.env.API_SERVER_HOST = process.env.API_SERVER_HOST_PROD;
process.env.API_SERVER_PORT = process.env.API_SERVER_PORT_PROD;
}
module.exports = {
entry: { ... },
output: { ... },
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: { ... }
},
{
loader: 'string-replace-loader',
options: {
multiple: [
{ search: '%%API_SERVER_HOST%%', replace: process.env.API_SERVER_HOST, flags: 'g' },
{ search: '%%API_SERVER_PORT%%', replace: process.env.API_SERVER_PORT, flags: 'g' }
]
}
}
]
}
]
},
plugins: [...]
};
At the top, we are checking the NODE_ENV environment variable and using it to determine which port the API is using. Then, in the options for our loader, we are instructing it to do a global RegEx search for the string, and replacing it with the dynamically-derived host and port.