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

253
Visualizações
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 à 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