How do I get access to environment

How do I get access to environment variables in test file?
15 Replies
MrBBot
MrBBotโ€ข2y ago
Hey! ๐Ÿ‘‹ Are you using one of the Miniflare testing environments? If so, you should be able to call the getMiniflareBindings() function to get an object containing environment variables? If not, regular process.env.VARIABLE_NAME might work?
Raiyan
RaiyanOPโ€ข2y ago
BTW, I have another question, how can I get country from the cf object without ignoring typescript type checking. I am not a wizard in typescript but still I couldn't make it work
Raiyan
RaiyanOPโ€ข2y ago
without commenting, it doesn't work
No description
No description
Raiyan
RaiyanOPโ€ข2y ago
Can it be an error? And it is not working with either methods, btw I am using .dev.vars to store my environment variables
MrBBot
MrBBotโ€ข2y ago
How are you running your tests? Ah this should be fixed in the next version of @cloudflare/workers-types released very soon, for now, I'd stick a // @ts-expect-error comment above which you'll need to remove next time you update @cloudflare/workers-types. I'll try remember to ping you when the release goes out. ๐Ÿ‘
Raiyan
RaiyanOPโ€ข2y ago
Sounds great BTW, can miniflare access .dev.vars and load environment variables?
MrBBot
MrBBotโ€ข2y ago
Yep, if you point --env-path/envPath to your .dev.vars file, it should load them: https://miniflare.dev/core/variables-secrets#env-files
๐Ÿ”‘ Variables and Secrets ยท Miniflare
Fun, full-featured, fully-local simulator for Cloudflare Workers
Raiyan
RaiyanOPโ€ข2y ago
This seems to be working!
MrBBot
MrBBotโ€ข2y ago
Nice! ๐ŸŽ‰
Raiyan
RaiyanOPโ€ข2y ago
I am sorry, I am asking too many questions but is there any way to verify fetchMock is working?
MrBBot
MrBBotโ€ข2y ago
No worries at all! Yep, fetchMock.disableNetConnect() will mean an exception is thrown whenever you haven't mocked a request and it tries to fetch from the internet. fetchMock.assertNoPendingInterceptors() will make sure that all your registered mocks have been hit.
Raiyan
RaiyanOPโ€ข2y ago
in my case, it seems to be hitting the public network
No description
Raiyan
RaiyanOPโ€ข2y ago
No description
MrBBot
MrBBotโ€ข2y ago
Hmmm, even with fetchMock.disableNetConnect()?
Raiyan
RaiyanOPโ€ข2y ago
So this is what I found. I have a separate worker file that does fetching, fetchmock is setup in the test file, I wanted the main api not to hit the internet, but it was not happening. So I tried to fetch the same url in the test file and fetchmock seems to be working. Is it the preferred use case and if so, how can I test my api that relies on external services?
Want results from more Discord servers?
Add your server