2

I have a NextJS app using a MongoDB. I just added Jest for testing. When I run the first test I get the following error:

Please define the MONGODB_URI environment variable inside .env.local

  4 |
  5 | if (!MONGODB_URI) {
> 6 |     throw new Error('Please define the MONGODB_URI environment variable inside .env.local');
    |           ^
  7 | }

I do have a file .env.local that has a MONGODB_URI and it works when I run my app locally and and on prod.

This is the test:

import React from 'react';
import ReactDom from 'react-dom';
import Home from '../../pages/index';
import { configure, shallow } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';

configure({ adapter: new Adapter() });

describe('<Home />', () => {
    it('should render Home', () => {
        const wrapper = shallow(<Home />);
        console.log('wrapper :', wrapper.debug());
    });
});

My jest.config.js:

module.exports = {
    clearMocks: true,
    coverageDirectory: 'coverage',
    moduleNameMapper: {
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
            '<rootDir>/__mocks__/fileMock.js',
        '\\.(css|less)$': 'identity-obj-proxy'
    },
    preset: '@shelf/jest-mongodb'

};

What am I missing here?

bonum_cete
  • 4,730
  • 6
  • 32
  • 56
  • Jest won't automatically pick up the env vars you have in `.env.local`. You'll need to set them when running your tests, or point Jest to the .env file you want to use. – juliomalves Feb 26 '21 at 19:48

3 Answers3

4

The .env.local is not loaded in the test environment, as you expect tests to produce the same results for everyone.

But you can still use environment variables for tests.

1. Option

You can use a env.test file and add the following to a globalSetup.js file

...
import { loadEnvConfig } from '@next/env'

export default async () => {
  const projectDir = process.cwd()
  loadEnvConfig(projectDir)
}
...

Make sure to setup the globalSetup.js file in the jest.config.js file:

...
globalSetup: ['<rootDir>/test/globalSetup.js'] // path to file
...

When you run your tests there should be a log in the console:

    Loaded env from C:\Users\XXX\XXX\XXX\nextjs\.env.test

More information here: Next.js Environment Variables Documentation

2. Option

You can use the dotenv package for the test env with the env.local file.

Add this in your jest-setup.js file:

import dotenv from 'dotenv'
dotenv.config({ path: '.env.local' })
Ado
  • 637
  • 1
  • 6
  • 17
1

in nextJS, I use .env.test for test environment.

iminiki
  • 2,549
  • 12
  • 35
  • 45
Someone Special
  • 12,479
  • 7
  • 45
  • 76
0

you will have to pass setupFiles option in the jest.config.js

module.exports = {
  setupFiles: ['env.local.config file'],
}

to use MONGODB_URI in the tests

ravi
  • 1,127
  • 9
  • 10