Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

492
Vistas
Jest can't find .env.local for MONGO_URI

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?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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' })
over 4 years ago · Santiago Trujillo Denunciar

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

over 4 years ago · Santiago Trujillo Denunciar

0

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda