使用mocha和node.js对私有函数进行单元测试 [英] unit testing of private functions with mocha and node.js

查看:209
本文介绍了使用mocha和node.js对私有函数进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mocha来对为node.js编写的应用程序进行单元测试

I am using mocha in order to unit test an application written for node.js

我想知道是否可以对未导出的单元测试函数进行单元测试模块。

I wonder if it's possible to unit test functions that have not been exported in a module.

示例:

我有很多像这样定义的函数在 foobar.js

I have a lot of functions defined like this in foobar.js

function private_foobar1(){
    ...
}

function private_foobar2(){
    ...
}

以及一些公开出口的函数:

and a few functions exported as public:

exports.public_foobar3 = function(){
    ...
}

测试用例的结构如下:

describe("private_foobar1", function() {
    it("should do stuff", function(done) {
        var stuff = foobar.private_foobar1(filter);
        should(stuff).be.ok;
        should(stuff).....

显然这不是工作,因为 private_foobar1 未导出。

Obviously this does not work, since private_foobar1 is not exported.

对私有方法进行单元测试的正确方法是什么? mocha有没有一些内置的方法呢?

What is the correct way to unit-test private methods? Does mocha have some built-in methods for doing that?

推荐答案

如果模块没有导出该功能,则不能由模块外部的测试代码调用。这是由于JavaScript的工作方式,而Mocha本身无法绕过这一点。

If the function is not exported by the module, it cannot be called by test code outside the module. That's due to how JavaScript works, and Mocha cannot by itself circumvent this.

在我确定测试私有函数是正确的事情的少数情况下,什么我已经完成了设置一些环境变量,我的模块检查它以确定它是否在测试设置中运行。如果它在测试设置中运行,那么它会导出我可以在测试期间调用的其他函数。

In the few instances where I determined that testing a private function is the right thing to do, what I've done is set some environment variable that my module checks to determine whether it is running in a test setup or not. If it runs in the test setup, then it exports additional functions that I can then call during testing.

这里使用了环境这个词。这可能意味着检查 process.env 或其他可以与模块通信的内容您现在正在测试。我必须执行此操作的实例位于RequireJS环境中,为此,我使用了 module.config

The word "environment" is loosely used here. It might mean checking process.env or something else that can communicate to the module "you're being tested now". The instances where I've had to do this were in a RequireJS environment, and I've used module.config for this purpose.

这篇关于使用mocha和node.js对私有函数进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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