How do I get access to environment

How do I get access to environment variables in test file?
15 Replies
MrBBot
MrBBotโ€ข15mo 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?
raiyansarker
raiyansarkerโ€ข15mo 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
raiyansarker
raiyansarkerโ€ข15mo ago
without commenting, it doesn't work
No description
No description
raiyansarker
raiyansarkerโ€ข15mo 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โ€ข15mo 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. ๐Ÿ‘
raiyansarker
raiyansarkerโ€ข15mo ago
Sounds great BTW, can miniflare access .dev.vars and load environment variables?
MrBBot
MrBBotโ€ข15mo 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
raiyansarker
raiyansarkerโ€ข15mo ago
This seems to be working!
MrBBot
MrBBotโ€ข15mo ago
Nice! ๐ŸŽ‰
raiyansarker
raiyansarkerโ€ข15mo ago
I am sorry, I am asking too many questions but is there any way to verify fetchMock is working?
MrBBot
MrBBotโ€ข15mo 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.
raiyansarker
raiyansarkerโ€ข15mo ago
in my case, it seems to be hitting the public network
No description
raiyansarker
raiyansarkerโ€ข15mo ago
No description
MrBBot
MrBBotโ€ข15mo ago
Hmmm, even with fetchMock.disableNetConnect()?
raiyansarker
raiyansarkerโ€ข15mo 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?