node.js - nodejs - 模拟模块,天真的方法

标签 node.js unit-testing mocking

目前我正在为使用 nodejs 编写的服务器端代码编写一些单元测试。

现在,我的自定义模块正在使用一些其他模块,我的或来自 nodejs 标准库的情况,我想模拟它们。首先,我用谷歌搜索了一些现有的解决方案,例如我发现:https://github.com/thlorenz/proxyquirehttps://github.com/mfncooper/mockery .

但今天我尝试使用天真的方法并做这样的事情:moduleUnderTest

var fs = require('fs');
exports.foo = function(){
  console.log("===foo===");
  fs.read();
}

和文件moduleUnderTestSpec:

var fs = require('fs');
var moduleUnderTests = require('../server/moduleUnderTests.js');

fs.read = function(){
  console.log("===read===");
}

当我运行 grunt jasmine_node 时,我可以看到:

===foo===
===read===

所以在这个简单的例子中,我可以将 fs 模块中的一个函数换成另一个。是否存在我的方法不起作用的情况?

最佳答案

先看看sinon因为它将帮助您轻松地模拟或 stub 功能。

当您在 Node.js 中require 模块时,模块会根据 docs on modules 进行缓存。 .

我在您的解决方案中看到的唯一问题是,如果您以后需要使用真正的 fs.read,您将无法使用,因为它丢失了。例如,您可以像这样使用 Sinon;

var fs = require('fs');
var sinon = require('sinon');

// mock fs.read
sinon
  .stub(fs, 'read')
  .returns("string data");

// test your code that uses fs.read
assert(fs.read.calledOnce);

// then restore
fs.read.restore();

关于node.js - nodejs - 模拟模块,天真的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19950243/

相关文章:

typescript - 如何模拟 ServiceBusError 异常以进行 Jest 测试?

c# - 调用服务时最小起订量单元测试失败

.net - 如何在 Moq 中调用作为参数传递的谓词?

javascript - 为什么 webRTC 这么不稳定?代码是相同的,但是 "sometimes it doesn' t 工作,有时它工作”?

node.js - 向特定 channel 发送消息,不起作用

c++ - Google Test 中的 FRIEND_TEST - 可能的循环依赖?

unit-testing - stub /模拟与服务虚拟化..?哎呀

java - SoapUI MockServices 返回 html 而不是 xml 响应

node.js - express res.download 提供 0 字节文件

javascript - 在每秒的精确开始处(或每秒特定的毫秒数)运行函数