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

后端 未结 8 1978
别跟我提以往
别跟我提以往 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:08

    This is not recommended practice, but if you can't use rewire as suggested by @Antoine, you can always just read the file and use eval().

    var fs = require('fs');
    const JsFileString = fs.readFileSync(fileAbsolutePath, 'utf-8');
    eval(JsFileString);
    

    I found this useful while unit testing client-side JS files for a legacy system.

    The JS files would set up a lot of global variables under window without any require(...) and module.exports statements (there was no module bundler like Webpack or Browserify available to remove these statements anyway).

    Rather than refactor the entire codebase, this allowed us to integrate unit tests in our client-side JS.

提交回复
热议问题