如何对需要其他模块的node.js模块进行单元测试 [英] How to unit test a node.js module that requires other modules

查看:127
本文介绍了如何对需要其他模块的node.js模块进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的例子,说明了我的问题的关键:

This is a trivial example that illustrates the crux of my problem:

var innerLib = require('./path/to/innerLib');

function underTest() {
    return innerLib.doComplexStuff();
}

module.exports = underTest;

我正在尝试为此代码编写单元测试。如何在不模仿 require 函数的情况下模拟 innerLib 的要求?

I am trying to write a unit test for this code. How can I mock out the requirement for the innerLib without mocking out the require function entirely?

编辑:所以这是我试图嘲笑全局需求并发现它甚至不会这样做:

So this is me trying to mock out the global require and finding out that it won't work even to do that:

var path = require('path'),
    vm = require('vm'),
    fs = require('fs'),
    indexPath = path.join(__dirname, './underTest');

var globalRequire = require;
require = function(name) {
    console.log('require: ' + name);
    switch(name) {
        case 'connect':
        case indexPath:
            return globalRequire(name);
            break;
    }
};

问题是需要函数里面underTest.js文件实际上并没有被模拟出来。它仍然指向全局 require 函数。所以我似乎只能在我正在进行模拟的同一个文件中模拟 require 函数。如果我使用全局 require 来包含任何内容,即使在我重写了本地副本之后,所需的文件仍将具有全局 require reference。

The problem is that the require function inside the underTest.js file has actually not been mocked out. It still points to the global require function. So it seems that I can only mock out the require function within the same file I'm doing the mocking. If I use the global require to include anything, even after I've overridden the local copy, the files being required will still have the global require reference.

推荐答案

你现在可以!

我发布了 proxyquire ,它将在您测试时覆盖模块中的全局需求。

I published proxyquire which will take care of overriding the global require inside your module while you are testing it.

这意味着您需要不需要更改代码才能为所需模块注入模拟。

This means you need no changes to your code in order to inject mocks for required modules.

Proxyquire有一个非常简单的api,它允许解析你试图测试的模块,并通过一个简单的步骤传递模拟/存根以获得所需的模块。

Proxyquire has a very simple api which allows resolving the module you are trying to test and pass along mocks/stubs for its required modules in one simple step.

@Raynos是对的传统上你不得不求助于不太理想的解决方案来实现这一目标或者做自下而上的开发

@Raynos is right that traditionally you had to resort to not very ideal solutions in order to achieve that or do bottom-up development instead

这是我创建proxyquire的主要原因 - 允许顶级道n测试驱动开发没有任何麻烦。

Which is the main reason why I created proxyquire - to allow top-down test driven development without any hassle.

查看文档和示例,以判断它是否符合您的需求。

Have a look at the documentation and the examples in order to gauge if it will fit your needs.

这篇关于如何对需要其他模块的node.js模块进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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