node.jsjasminegulp

How to run NodeJS unit tests with a different NODE_PATH


The question

Can I run unit tests from within Node/Gulp which have a different NODE_PATH than what has been inherited from the environment?

The issue

I have a project which is being run from within a Rhino based application, where require loads scripts from a set of defined locations.

I want to have unit tests for my components. In order to run those tests I need to be able to call my scripts from the Node environment. But that ends with error similar to this:

Error: Cannot find module 'lib/foo/foo.js'

This is because my scripts contain require(foo/foo)... that would be fine if NODE_PATH would have contained lib. The issue here is that I only want this folder to be present for unit tests, not for other gulp tasks.


I guess the issue I am facing is that all test runners I came across (e.g. karma) are browser based. So my question might as well be: Is there a test runner which runs pure NodeJS tests?


Solution

  • I have invested a few hours into finding answer to my question. Node is quite hostile when it comes to manipulating NODE_PATH during runtime.

    So the answer to my own question is: No, gulp-based tests can not run with a different NODE_PATH, unless those tests spawn a new process.


    I was not able to find convenient test runner which is able to spawn node with a different environment. I was able to write my own code to run unit tests in a new process, but that had far too many "rough edges".

    In the end I went for app-module-path module to keep things simple (I didn't want a special wrapper shell script). That is not exactly what I was looking for, but it is pretty close.


    UPDATE 2025 (to sums up what I have actually ended up with back in the day): I wrote my own require implementation and from within the tests I was loading scripts via script.runInNewContext that allows me to specify custom globals (including the custom require implementaion and other RhinoJS globals).