2018年8月17日 星期五

[NodeJS] Import Module Without Executing the Script

When working on my nodeJS project, I encounter some kind of difficulties on the following scenario

I wrote an expressJS application, which in turn being allocated to be unit tested, the problem is I want to pass the expressJS application to my test program, so I figure out I can export the "app" from the "index.js", so I add

export default app


in my index.js, so finally I can export the app variable and import it to my unit test. But the problem is when I import the module, I also execute the code associated with module which is not what I want, is there anything like Python's if __name__ == "__main__"?

I just want to import the module without executing it, so I end up with the following strategies

I wrap all the actions in a function and return my app at the end

export function initApp() {
   app.use...
   app.use...
   return app;
}

Then I add this important snippet

if (require.main === module) {
    initApp();
}

This is important ! It tells nodeJS only if this file being run by node can the initApp being executed, so in my unit test case, I could just safely import this module without unintentionally execute the initApp function

沒有留言:

張貼留言