如何访问和测试node.js模块中的内部(非导出)功能? [英] How to access and test an internal (non-exports) function in a node.js module?

查看:102
本文介绍了如何访问和测试node.js模块中的内部(非导出)功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在nodejs中测试内部(即未导出)函数(最好使用mocha或jasmine)。我不知道!

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 module like that:

function exported(i) {
   return notExported(i) + 1;
}

function notExported(i) {
   return i*2;
}

exports.exported = exported;

以下测试(摩卡):

var assert = require('assert'),
    test = require('../modules/core/test');

describe('test', function(){

  describe('#exported(i)', function(){
    it('should return (i*2)+1 for any given i', function(){
      assert.equal(3, test.exported(1));
      assert.equal(5, test.exported(2));
    });
  });
});

有没有办法对 notExported 函数没有实际导出它,因为它不打算暴露?

Is there any way to unit test the notExported function without actually exporting it since it's not meant to be exposed?

推荐答案

重新布线模块绝对是答案。

这是我访问未导出函数并测试它的代码使用Mocha。

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

application.js:

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');


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();
  });
});

这篇关于如何访问和测试node.js模块中的内部(非导出)功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆