Description
Increasing Access
We want our tests to use the same environment as the app itself so that we can catch potential issues in the app.
Feature enhancement details
The variables which are declared in the .env
file do not get loaded into the window.process.env
variable when we are running tests. Consequently, the getConfig
utility always returns undefined
.
On the actual web app, we pass these configuration variables from the backend to the frontend by printing the values into a JS <script>
tag in the index.html
file. That script is executed by the browser which sets the window.process.env
.
p5.js-web-editor/server/views/index.js
Lines 16 to 39 in c7492d3
Possible Solutions and Workarounds
1. Fallback values
This is the current workaround. If a value is required then we have to set a default in the code.
We have this same line in 3 different files:
2. Setup in Jest
If we need specific values for a test, we can set them using Jest utils beforeEach
, beforeAll
, etc.
beforeAll(() => {
window.process.env.PREVIEW_URL = 'http://localhost:8002';
});
This is good because it allows us to test multiple values. ie, see that we do the correct thing if an option is false
and if it's true
. But it feels silly when we are just setting the same values which already exist in the .env
.
3. Load in the .env
We can load the variables from the .env
file into window.process.env
by adding two lines to the client/jest.setup.js
file.
import dotenv from 'dotenv';
dotenv.config();
But this alone doesn't work with our current setup because all .env
variables are read a string
types. We would need to implement the same sort of casting to boolean
and number
that we do in the server/views/index.js
file currently. And ideally do that without repeating ourselves. One approach would be to keep the variables as string
when passing from backend to frontend and to do all the casting on the frontend.