Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

502
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda