Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!