Stubbing Cloudflare Secrets for Unit Tests

I understand that Cloudflare Secrets & Environment variables are injected by the Cloudflare Worker runtime, and have no problem with using them via wrangler dev – I want to be able to override/stub them when locally running unit tests written in Typescript using Mocha. I’ve not had any success with any combination of the following:

  • overriding the global scope within the test runner: mocha --globals global
  • dumping the value of global into a new variable and using that throughout: const globalAny:any = global;
  • simply declaring the variable at the top and overriding it in the tests: declare var SIGNING_KEY_CLOUDFLARE: any;
  • doing the same as the above except with let — this unfortunately overrides the value set by the runtime

To summarize, could I get an answer on the following:

  1. Are secrets/environment vars written to the global object in the Cloudflare Worker runtime? If not, what are they written to?
  2. How can I override that object (or simply those values) in my local unit tests?


I’ve also been wondering the same thing, did you ever find a solution for this?

I end up with this solution

worker = new Cloudworker(workerScript, {
  bindings: {
    ENV_VARIAVLE_1: "your env", 
    ENV_VARIAVLE_2: process.env["ENV_VARIAVLE_2"],  # or load the global ENV 

If you’re using mocha, you can refer to this article to load ENV.