How can I use functions and objects without require them in NodeJS

I have been studying NodeJS for about a year and today I found something strange for me. We all know that in order to use a module (function, object or variable) in another module we must export and import it except for the native modules like String, Number, Promise, etc. I installed an external package for unit testing called Jest.

The strange thing here is that I have created two test modules called: logic.js and logic.test.js, in none I have imported the Jest module, however I can access all its methods. Let's show some code:

logic.js

module.exports.add = function(a, b){
    return a + b;
}

logic.test.js

const lib = require('../logic')

test('Add - Should return the sum of two numbers', () => {
    const result = lib.add(1,3);
    expect(result).toBe(4);
});

As you can see in logic.test.js I have access to expect and test methods and i have not impoted nothing about Jest.

The questions here are:

Upvotes: 0

Views: 1490

Answers (1)

Hammerbot
Hammerbot

Reputation: 16344

As Jonas W stated in the comments, they make use of the global variable that is common to all your application.

The use of the global variable is very simple

test.js

global.myObject = 'MyMan'

app.js

require('./test')

console.log(myObject)

Loading app.js will render MyMan

You might say that I actually import the test module and that Jest does not.

The thing is that you execute your node application using node yourFile.js but you instanciate your jests tests with the jest command line.

It's the jest command line that handles the binding between its framework (the expect and test methods.) and your script.

Is it a good practice?

I would say no. Except if you plan to make a library like Jest that have its own command line launcher and that you want to give tools like that to the users of your library.

The power of Node lives into the module organization, don't be afraid to use them.

Upvotes: 3

Related Questions