Unable to load .env file when running jest + miniflare

I have a project running on Cloudflare Worker and I’m using jest and miniflare for unit-test.

However I’m unable to load env var from .env file into jest environment when running npm run test.

My wrangler.toml [miniflare] config:

[miniflare]
cache_persist = true
durable_objects_persist = true
kv_persist = true
env_path = ".env"

package.json:

  "scripts": {
    "build": "node build.js",
    "dev": "miniflare --live-reload --debug --modules dist/index.mjs",
    "dev:remote": "wrangler dev",
    "test": "npm run build && node --experimental-vm-modules --no-warnings node_modules/jest/bin/jest.js",
    "types:check": "tsc && tsc -p test/tsconfig.json",
    "deploy": "wrangler publish"
  },

.env file:

ADMIN_TOKEN=xxxxxx

however process.env.ADMIN_TOKEN is undefined when running in jest.

Hi @touchapon

What about env.ADMIN_TOKEN?

Hey, I’m facing the same problem.
With wrangler I can read the env variables, but under the miniflare the env is undefined.

  async fetch(request, env, _ctx) {
    // Only accept a PUT request
    if (request.method !== 'PUT') {
      return new Response('{"error": "Bad request!"}');
    }
    console.log('Environment', env);
  }

I tried multiple things, such as: .env, wrangler.toml, none of them worked. In miniflare + jest the env variable always undefined.

Any clue?