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

248
Vistas
NodeJS Jest : Testing function that imports module using require.main.require

I am trying to write unit testing using Jest for a Node JS project. It was importing all the modules using require.main.require

Below are the simulation of the issue. Code can be found here: https://stackblitz.com/edit/node-jest-demo?file=index.js

I have the following test file present in my root directory in which I am importing index.js

./sample.pass.test.js

const { checkUser } = require('./index');

console.log(checkUser); // This is purely to check If i can access checkUser from this file or not

describe('Testing...', () => {
  it('Should pass', () => {
    expect(0).toBe(0);
  });
});

In my index.js I am importing another function using require.main.require

const { getUserById } = require.main.require('./models/UserModel');

function checkUser(id) {
  const user = getUserById(id);
  return user ? 'Found' : 'Not Found';
}

module.exports.checkUser = checkUser;

The above test case is passing. But If I were to place the same test file in some other directly (like _test_ ) then it fails.

E.g.: ./__test__/sample.fail.test.js

Notice here I adjusted require statement of index since it is now one level up

const { checkUser } = require('../index');

console.log(checkUser);

describe('Testing...', () => {
  it('Should pass', () => {
    expect(0).toBe(0);
  });
});

The result shows it is unable to access UserModel.

Cannot find module './models/UserModel' from '__tests__/sample.fail.test.js'

    Require stack:
      index.js
      __tests__/sample.fail.test.js

    > 1 | const { getUserById } = require.main.require('./models/UserModel');
        |                                      ^
      2 |
      3 | function checkUser(id) {
      4 |   const user = getUserById(id);

What could be the solution in this case?

Thank in advance!

about 4 years ago · Juan Pablo Isaza
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