Loading environment variables in NextJS tests
This took me a while to figure out, so it’s here in case the Google gods pick it up, and as a reminder to myself when I forget about it the next time.
By default when running tests in a Next.js environment with Jest etc, the environment variables that are defined in .env
files (e.g. env.local
and so on) don’t get loaded.
That’s a PITA, because if you’ve gone to the trouble of creating .env
vars, it’s because you need them.
The solution is simple, if not exactly obvious. The first step is to import loadEnvConfig
from @next/env
at the top of every test file:
import { loadEnvConfig } from '@next/env'
And then force the vars to be loaded before each test run - the simplest way to do this is with a beforeEach()
block (this assumes you’re using Jest, but it’s the same approach for other test frameworks):
beforeEach( () => {
loadEnvConfig(process.cwd())
});
With this in place, you’ll have access to all the vars via the usual process.env.<var_name>
approach.