How to access and test an internal (non-exports) function in a node.js module?

后端 未结 8 2007
别跟我提以往
别跟我提以往 2020-12-12 09:31

I\'m trying to figure out on how to test internal (i.e. not exported) functions in nodejs (preferably with mocha or jasmine). And i have no idea!

Let say I have a mo

8条回答
  •  余生分开走
    2020-12-12 10:15

    The trick is to set the NODE_ENV environment variable to something like test and then conditionally export it.

    Assuming you've not globally installed mocha, you could have a Makefile in the root of your app directory that contains the following:

    REPORTER = dot
    
    test:
        @NODE_ENV=test ./node_modules/.bin/mocha \
            --recursive --reporter $(REPORTER) --ui bbd
    
    .PHONY: test
    

    This make file sets up the NODE_ENV before running mocha. You can then run your mocha tests with make test at the command line.

    Now, you can conditionally export your function that isn't usually exported only when your mocha tests are running:

    function exported(i) {
       return notExported(i) + 1;
    }
    
    function notExported(i) {
       return i*2;
    }
    
    if (process.env.NODE_ENV === "test") {
       exports.notExported = notExported;
    }
    exports.exported = exported;
    

    The other answer suggested using a vm module to evaluate the file, but this doesn't work and throws an error stating that exports is not defined.

提交回复
热议问题