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

查看:36
本文介绍了如何访问和测试 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;

还有以下测试(摩卡):

And the following test (mocha):

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?

推荐答案

rewire 模块绝对是回答.

这是我的代码,用于访问未导出的函数并使用 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');


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

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

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