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

后端 未结 8 1996
别跟我提以往
别跟我提以往 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条回答
  •  猫巷女王i
    2020-12-12 09:54

    The rewire module is definitely the answer.

    Here's my code for accessing an unexported function and testing it using Mocha.

    application.js:

    function logMongoError(){
      console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
    }
    

    test.js:

    var rewire = require('rewire');
    var chai = require('chai');
    var should = chai.should();
    
    
    var app = rewire('../application/application.js');
    
    
    var logError = app.__get__('logMongoError'); 
    
    describe('Application module', function() {
    
      it('should output the correct error', function(done) {
          logError().should.equal('MongoDB Connection Error. Please make sure that MongoDB is running.');
          done();
      });
    });
    

提交回复
热议问题