【发布时间】:2013-07-03 07:55:37
【问题描述】:
假设我有这种情况(架构)
layer1 -> layer2 -> layer3
层只是普通的 node.js 模块(有一些导出的功能)
Layer1 需要 layer2 并调用他的函数,而 layer2 需要 layer3 并调用他的函数。
我想测试 layer1 中的函数,但也要模拟 layer3(我在 layer1 中的函数调用被传播到 layer3 并且我想模拟这个)。
最好的方法是什么? 我看过这个模块:https://github.com/thlorenz/proxyquire,但我认为它不支持像我的示例那样深入到 2 级或更高级别时进行模拟。
感谢您的任何建议!
【问题讨论】:
-
为什么你认为 proxyquire 不能在 3 层深的地方工作?
-
正如我在文档和我的示例中看到的那样,您必须拥有该模拟模块的实例 (var foo = proxyquire('./foo', { 'path': pathStub });) .. .但我无法从我的测试中进入那个layer3模块,因为我没有测试他......如果你有一些例子(源代码或伪代码)请写出来:)
-
layer2 是否需要 layer3 像这样:require('module3') 或 require('./module3')?
-
在 NodeJS 中模拟模块有时真的很棘手,因为它很容易陷入依赖地狱。我建议您尝试将您的模块与 DI 微框架松散地绑定,例如 c9-architect。我发现一旦开始以这种方式组织代码,测试代码就容易多了,并且从 npm 安装的节点模块可以通过使用 选项参数。
-
AndyD:它是 require('./module3')。模块不在 package.json 中,而只在我的代码中,所以它是它们的相对路径。
标签: javascript node.js unit-testing mocking integration-testing